.Net魔法堂:发个待附件的邮件
由于工作需要最近把邮件发送封装成WebService,现在把代码记录在此,以便日后查阅。
二、二话不说写代码
复制代码
private void _SendMail(string form, string pw, string subject, string[] to, string[] cc, string body, string attachmentName, byte[] attachment)
{
SmtpClient client = new SmtpClient(SMTP服务地址, SMTP服务端口);
client.UseDefaultCredentials = true;
client.Credentials = new NetworkCredential(form, pw); // 验证信息要与邮件发送源地址一致,否则无法发送
client.DeliveryMethod = SmtpDeliveryMethod.Network;
MailMessage message = new MailMessage();
message.From = new MailAddress(form);
foreach (string toItem in to)
{
message.To.Add(toItem);
}
foreach (string ccItem in cc)
{
message.CC.Add(ccItem);
}
message.Subject = subject;
message.SubjectEncoding = Encoding.UTF8;
message.Body = body;
message.BodyEncoding = Encoding.UTF8;
message.IsBodyHtml = true;
message.Priority = MailPriority.High;
Stream stream = null;
Attachment data = null;
try
{
if (attachment != null && attachment.Length > 0)
{
stream = new MemoryStream(attachment);
data = new Attachment(stream, attachmentName, System.Net.Mime.MediaTypeNames.Application.Octet);
message.Attachments.Add(data);
}
client.Send(message);
}
finally
{
if (null != stream)
{
stream.Close();
}
}
}
复制代码
三、三种发送方式
发送邮件有三种方式:
①. client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
直接通过远程SMTP服务器发送邮件
②. client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.PickupDirectoryFromIis;
通过本机的IIS服务器的SMTP服务发送邮件(后续在研究什么配置SMTP服务器?)
③. client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.SpecifiedPickupDirectory;
将邮件发送到本机指定目录中,再通过其他手段(如通过FTP)发送到目的地
上一篇: 鳗鱼养殖苗价格便宜并且又好吃?实在是想不到想不到啊
下一篇: 喝姜母茶的好处