csharp 使用链接方法模式使用C#.NET发送电子邮件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 使用链接方法模式使用C#.NET发送电子邮件相关的知识,希望对你有一定的参考价值。
namespace LibMailer {
using System.Net;
using System.Net.Mail;
/// <summary>
/// Usage
/// var mailer = new Mailer(host: "smtp.mail.yahoo.com", port: 587)
/// .From(address: "g.seref@yahoo.ca").To(address: "serefguneysu@gmail.com")
/// .Subject(subject: "Konu")
/// .Body(body: "<h1>GÖVDE</h1>", isHtml: true)
/// .Html()
/// .Login(user: "g.seref@yahoo.ca", password: "y0urP@assw0rd", enableSsl: true)
/// .Ssl()
/// .Send();
/// </summary>
public class Mailer {
private SmtpClient client = new SmtpClient();
private NetworkCredential credentials = new NetworkCredential();
private MailAddress sender { get; set; }
private MailAddress receiver { get; set; }
private MailMessage message = new MailMessage();
public Mailer(string host, int port) {
client.Host = host;
client.Port = port;
}
public Mailer Login(string user, string password, bool enableSsl = false) {
credentials.UserName = user;
credentials.Password = password;
client.Credentials = credentials;
client.EnableSsl = enableSsl;
return this;
}
public Mailer Ssl() {
client.EnableSsl = true;
return this;
}
public Mailer From(string address) {
sender = new MailAddress(address);
message.From = sender;
return this;
}
public Mailer To(string address) {
receiver = new MailAddress(address);
message.To.Add(receiver);
return this;
}
public Mailer Subject(string subject) {
message.Subject = subject;
return this;
}
public Mailer Body(string body, bool isHtml = false) {
message.Body = body;
message.IsBodyHtml = isHtml;
return this;
}
public Mailer Html() {
message.IsBodyHtml = true;
return this;
}
public Mailer Send() {
client.Send(message);
return this;
}
public MailMessage Mail(string from, string to, string subject, string body) {
var sender = new MailAddress(from);
var receiver = new MailAddress(to);
var msg = new MailMessage(from: sender, to: receiver);
msg.Subject = subject;
msg.Body = body;
return msg;
}
}
class Program {
static void Main(string[] args) {
new Mailer(host: "smtp.mail.yahoo.com", port: 587)
.From(address: "g.seref@yahoo.ca").To(address: "serefguneysu@gmail.com")
.Subject(subject: "Konu")
.Body(body: "<h1>GÖVDE</h1>", isHtml: true)
.Login(user: "g.seref@yahoo.ca", password: "y0urP@assw0rd", enableSsl: true)
.Send();
new Mailer(host: "smtp.mail.yahoo.com", port: 587)
.From(address: "g.seref@yahoo.ca").To(address: "serefguneysu@gmail.com")
.Subject(subject: "Konu")
.Body(body: "<h1>GÖVDE</h1>", isHtml: true)
.Html()
.Login(user: "g.seref@yahoo.ca", password: "y0urP@assw0rd")
.Ssl()
.Send();
}
}
}
以上是关于csharp 使用链接方法模式使用C#.NET发送电子邮件的主要内容,如果未能解决你的问题,请参考以下文章