调用发送
try { P2BEmail email = new P2BEmail(); email.fromEmail = txtfromEmail.Text; // QQ邮箱 email.fromPwd = txtfrompwd.Text; // QQ邮箱授权码 email.emailType = txtemailtype.Text; // smtp.qq.com email.SendEmail(txttoemail.Text, txtsubject.Text, txtbody.Text, ""); txtmessage.Text = "成功"; } catch (Exception ex) { txtmessage.Text = ex.Message + ex.StackTrace; }
邮件发送逻辑
public class P2BEmail { public string fromEmail = "XX@qq.com";//邮件发送方 public string fromPwd = "XXXXXXXXXX"; //邮件发送方密码/QQ授权码 public string emailType = "smtp.qq.com";//邮件类型 smtp.163.com.cn; smtp.qq.com.cn; smtp.126.com.cn; smtp.sina.com.cn /// <summary> /// 发送电子邮件 /// </summary> /// <param name="toEmail">接收方电子邮件</param> /// <param name="subject">邮件标题</param> /// <param name="body">邮件内空</param> public void SendEmail(string toEmail, string subject, string body, string attFile) { MailAddress addrFrom = new MailAddress(fromEmail, fromEmail); MailAddress addrTo = new MailAddress(toEmail, toEmail); MailMessage mm = new MailMessage(addrFrom, addrTo); mm.BodyEncoding = Encoding.UTF8; mm.IsBodyHtml = true; mm.Subject = subject; mm.Body = body; if (!string.IsNullOrEmpty(attFile)) { Attachment att = new Attachment(attFile, MediaTypeNames.Application.Octet); ContentDisposition cd = att.ContentDisposition; cd.CreationDate = File.GetCreationTime(attFile); cd.ModificationDate = File.GetLastWriteTime(attFile); cd.ReadDate = File.GetLastAccessTime(attFile); mm.Attachments.Add(att);//添加附件 } NetworkCredential nc = new NetworkCredential(fromEmail, fromPwd); SmtpClient smtp = new SmtpClient(emailType); smtp.EnableSsl = true; //启用SSl
// 随请求一起发送 smtp.UseDefaultCredentials = false;
// 邮件账户凭证 smtp.Credentials = nc;
// 邮件发送方式-网络发送 smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
// 服务器证书验证回调 ServicePointManager.ServerCertificateValidationCallback =delegate (Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; }; try { smtp.Send(mm); } catch (SmtpFailedRecipientException) { smtp.Dispose(); return; } catch (Exception ex) { throw ex; } smtp.Dispose(); } }
下载地址:源码下载.zip