【发布时间】:2016-05-16 07:34:29
【问题描述】:
我想使用 System.Web.Mail.MailMessage 和 System.Web.Mail.SmtpMail 类发送电子邮件。 我知道这是一个已弃用的类,但使用 System.Net.Mail 对我来说不是一个选项。
到目前为止,我能够发送 html 格式的邮件,但我无法在发送时将图像嵌入到我的电子邮件中。
这是我迄今为止尝试过的;
private static void SendMailMethod(string mailServer, int mailServerPort, string userName, string password)
{
const string SMTP_SERVER = "http://schemas.microsoft.com/cdo/configuration/smtpserver";
const string SMTP_SERVER_PORT =
"http://schemas.microsoft.com/cdo/configuration/smtpserverport";
const string SEND_USING = "http://schemas.microsoft.com/cdo/configuration/sendusing";
const string SMTP_USE_SSL = "http://schemas.microsoft.com/cdo/configuration/smtpusessl";
const string SMTP_AUTHENTICATE =
"http://schemas.microsoft.com/cdo/configuration/smtpauthenticate";
const string SEND_USERNAME =
"http://schemas.microsoft.com/cdo/configuration/sendusername";
const string SEND_PASSWORD =
"http://schemas.microsoft.com/cdo/configuration/sendpassword";
var mailMessage = new System.Web.Mail.MailMessage();
mailMessage.Fields[SMTP_SERVER] = mailServer;
mailMessage.Fields[SMTP_SERVER_PORT] = mailServerPort;
mailMessage.Fields[SEND_USING] = 2;
mailMessage.Fields[SMTP_USE_SSL] = false;
mailMessage.Fields[SMTP_AUTHENTICATE] = 0;
mailMessage.Fields[SEND_USERNAME] = userName;
mailMessage.Fields[SEND_PASSWORD] = password;
mailMessage.From = "abc@xyz.com";
mailMessage.To = "abc@xyz.com";
mailMessage.Subject = "Test mail:";
mailMessage.BodyFormat = MailFormat.Html;
var mailAttachment = new MailAttachment("E:\\imageToEmbed.jpg");
mailMessage.Attachments.Add(mailAttachment);
mailMessage.Attachments.Add(new MailAttachment("E:\\TestAttachmentFile.txt"));
var htmlBody =
"<!DOCTYPE html PUBLIC \" -//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">" +
"<html xmlns = \"http://www.w3.org/1999/xhtml\" >" +
" <head >" +
"<meta http - equiv = \"content-type\" content = \"text/html; charset=UTF-8\" />" +
"</head >" +
"<body style = \"font-family: Segoe UI; text-align:left;\" >" +
"Following is an embedded image:" +
"<br />" +
"<img alt = \"\" src = \"imageToEmbed.jpg\" />" +
"</body >" +
"</html >";
mailMessage.Body = htmlBody;
try
{
SmtpMail.Send(mailMessage);
Console.WriteLine("Mail sent");
}
catch (Exception ex)
{
Console.WriteLine("Error:" + ex.ToString());
throw ex;
}
}
此代码发送电子邮件,但不是显示图像,而是显示带有十字的小方块。 如何将此“imageToEmbed.jpg”嵌入到我的电子邮件中。
【问题讨论】:
-
@photowalker,您分享的链接中的答案对我不起作用。因为我没有使用 System.Net.Mail 名称空间。我正在使用 System.Web.Mail.MailMessage 类发送电子邮件
-
为什么你被限制在那个过时的类?您在使用 .Net 1.1 吗?
-
我仅限于这个过时的类,因为 System.Net.Mail 中的新类不允许我使用 SSL 安全性发送邮件。我已经问过这个here