引用命名空间:using System.Net.Mail;
新建一个SmtpClient 类的实例,让其使用指定的 SMTP 服务器发送电子邮件。
SmtpClient client = new SmtpClient(server);
新建一个MailMessage对象来配置要发送的各种信息,发件箱、收件箱、附件、主题、正文等等
MailMessage message = new MailMessage();
message.From = fromAddress; //发件地址
message.To.Add(toAddress); //收件地址
message.CC.Add(ccAddress); //抄送地址
message.Attachments.Add(new Attachment("test.txt")); //附件
message.Body = body; //邮件正文,string类型
message.BodyEncoding = System.Text.Encoding.UTF8; //正文编码方式
message.Subject = subject; //邮件主题
message.SubjectEncoding = System.Text.Encoding.UTF8; //主题编码方式
而后使用SmtpClient的Send方法发送邮件
client.Send(message);
以下为完整的示例代码:
public static void SendMail(string body) { SmtpClient client = new SmtpClient(server); client.UseDefaultCredentials = true; MailAddress from = new MailAddress("from@microsoft.com"); MailAddress to = new MailAddress("to@microsoft.com");
MailAddress cc = new MailAddress("cc@microsoft.com");
MailMessage message = new MailMessage(); message.From = from; message.To.Add(to); message.CC.Add(cc);
message.Attachments.Add(new Attachment("test.txt")); message.Body = body; message.BodyEncoding = System.Text.Encoding.UTF8; message.Subject = subject; message.SubjectEncoding = System.Text.Encoding.UTF8; client.Send(message); message.Dispose(); message = null; client.Dispose(); client = null; }