c#:SMTP發送帶圖片郵件


使用SMTP發送郵件
發送的郵件為本地html文件,html中的圖片為本地圖片

主體函數,根據傳入的bool參數發送不同的模板

internal class FeedbackMail
{
public MailMessage mailMessage = new MailMessage();
public SmtpClient smtpClient;
public int senderPort = 587;
public String senderServerHost = "mail.abc.com";
public String senderPassword = "abc";
public String senderUsername = "aaa";

public void SendMail(Boolean isSuccess)
{
String[] members = XmlReader.GetElementFromXml("SendMailTo").Split(';');
foreach (var member in members)
{
mailMessage.To.Add(member);
}
mailMessage.From = new MailAddress("abc@abc.com");
mailMessage.Subject = "EmailTest";
AlternateView htmlBody;
if (isSuccess)
{
var reader = new StreamReader(@"C:\MailForSuccess.html", Encoding.Default);
var mailBody = reader.ReadToEnd().ToString();
htmlBody = AlternateView.CreateAlternateViewFromString(mailBody, null, "text/html");
}
else
{
var reader = new StreamReader(@"C:\MailForFailure.html", Encoding.Default);
var mailBody = reader.ReadToEnd().ToString();
htmlBody = AlternateView.CreateAlternateViewFromString(mailBody, null, "text/html");
}
LinkedResource lrImage = new LinkedResource(@"C:\AvePoint.png", "image/gif");
LinkedResource lrImage2 = new LinkedResource(@"C:\MSPartner.png", "image/gif");
lrImage.ContentId = "AvePoint";
lrImage2.ContentId = "MSPartner";
htmlBody.LinkedResources.Add(lrImage);
htmlBody.LinkedResources.Add(lrImage2);
mailMessage.AlternateViews.Add(htmlBody);
mailMessage.IsBodyHtml = true;
mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
mailMessage.Priority = MailPriority.Normal;
Send();
}

public void Send()
{
try
{
if (mailMessage != null)
{
smtpClient = new SmtpClient();
smtpClient.Host = senderServerHost;
smtpClient.Port = senderPort;
smtpClient.UseDefaultCredentials = false;

smtpClient.Credentials = new System.Net.NetworkCredential(senderUsername, senderPassword);

smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtpClient.Send(mailMessage);
Console.WriteLine("Send Success");
}
}
catch (Exception ex)
{
Console.WriteLine("Send Fail");
Console.WriteLine(ex.Message);
}
}
}

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
  © 2014-2022 ITdaan.com 联系我们: