要在 .NET 中发送电子邮件,请使用 SmtpClient 和 MailMessage 和 Attachment 类。
MailMessage 类表示邮件消息的内容。 SmtpClient 类将电子邮件传输到您指定用于邮件传递的 SMTP 主机。您可以使用 Attachment 类创建邮件附件。
假设您有一个带有单独样式表和图像的 HTML 通讯,您需要创建一个带有 HTML 正文内容的 MailMessage 并将外部文件添加为附件。您需要设置每个附件的 ContentId 属性,并更新 HTML 中的引用以使用它。
HTML 正文中指向附件的 href 使用 cid: 方案。对于 id 为“xyzzy”的附件,href 为“cid:xyzzy”。
使用 HTML 正文构造 MailMessage:
string content; // this should contain HTML
// Create a message and set up the recipients.
MailMessage message = new MailMessage(
"from@example.com",
"to@example.com");
message.Subject = "The subject.";
message.Body = content;
message.IsBodyHtml = true;
构造带有附件的MailMessage:
string file = "data.xls";
// Create a message and set up the recipients.
MailMessage message = new MailMessage(
"from@example.com",
"to@example.com");
message.Subject = "The subject.";
message.Body = "See the attached file";
// Create the file attachment for this e-mail message.
Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
data.ContentId = Guid.NewGuid().ToString();
// Add time stamp iformation for the file.
ContentDisposition disposition = data.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(file);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
// Add the file attachment to this e-mail message.
message.Attachments.Add(data);
使用 SmtpClient 发送 MailMessage:
//Send the message.
SmtpClient client = new SmtpClient(server);
// Add credentials if the SMTP server requires them.
client.Credentials = CredentialCache.DefaultNetworkCredentials;
client.Send(message);