C#邮件发送
以前写的邮件收发是用的socket来做的,现在为了开发效率,还是用微软的邮件发送类方便,只要传对了参数,发送就这样成功了。
需要注意的是,现在有很多新的邮箱都不支持smtp方式了,只能用web形式的。还好,网上说2006年前的邮箱是没有问题的,也没有时间去试真假,有遇到的不妨留言分享一下。。
/// <summary> |
/// 邮件发送方法 |
/// </summary> |
/// <param name="mailFrom">发件人地址</param> |
/// <param name="mailTo">收件人地址</param> |
/// <param name="mailSubject">主题</param> |
/// <param name="mailBody">邮件内容</param> |
/// <param name="mailAttch">附件路径</param> |
/// <param name="mailSmtp">服务器</param> |
/// <param name="mailCode">密码(对称加密过的)</param> |
/// <param name="mailPriority">优先级</param> |
/// <param name="mailCopy">添加抄送电子邮件</param> |
private void fMailSend(string mailFrom, string mailTo, string mailSubject, string mailBody, string mailAttch, string mailSmtp, string mailCode, string mailPriority, string mailCopy) |
{ |
//用附件发送给客户 |
MailAddress EmailFrom = new MailAddress(mailFrom); //发件人地址 |
MailAddress EmailTo = new MailAddress(mailTo);//收件人地址 |
MailMessage Email = new MailMessage(EmailFrom, EmailTo); |
Email.Priority = (mailPriority == "High") ? MailPriority.High : MailPriority.Normal; //设置优先级 |
Email.Subject = mailSubject;//主题 |
Email.Body = mailBody;//邮件内容 |
if (string.IsNullOrEmpty(mailCode)) |
Email.CC.Add(mailCopy); //添加抄送电子邮件 |
string file = mailAttch;//附件路径 |
Attachment data = new Attachment(file, System.Net.Mime.MediaTypeNames.Application.Octet); |
// 为文件添加发送时间 |
System.Net.Mime.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); |
// 添加附件到邮件 |
Email.Attachments.Add(data); |
SmtpClient Client = new SmtpClient(mailSmtp); |
//验证 (Credentials 凭证) |
Client.Credentials = new System.Net.NetworkCredential(mailFrom, clsCryptography.fDecryptData(mailCode)); |
//处理待发的电子邮件的方法 (Delivery 发送,传输) |
Client.DeliveryMethod = SmtpDeliveryMethod.Network; |
try |
{ |
Client.Send(Email); |
btnPass.AddScript(clsSystem.fGetExtMsgAlert("系统提示", "测试发送成功!")); |
} |
catch (SmtpFailedRecipientsException ex) |
{ |
for (int i = 0; i < ex.InnerExceptions.Length; i++) |
{ |
SmtpStatusCode status = ex.InnerExceptions[i].StatusCode; |
if (status == SmtpStatusCode.MailboxBusy || status == SmtpStatusCode.MailboxUnavailable) |
{ |
btnPass.AddScript(clsSystem.fGetExtMsgAlert("系统提示", "发送失败,5秒钟后重试..")); |
System.Threading.Thread.Sleep(5000); |
Client.Send(Email); |
} |
else |
{ |
btnPass.AddScript(clsSystem.fGetExtMsgAlert("系统提示", "发送邮件失败,{0}" + ex.FailedRecipient[i].ToString().Trim() + "")); |
} |
} |
} |
} |