实现了Jmail组件的发送邮件
可是在测试 gmail 与 新163邮箱(本人2个163邮箱,其中一个是可以的) 的时候总是发送失败。
原因:
http://mail.163.com/news/163news061115.htm
而Gmail有SSl加密、还有端口的设置,不知道Jmail组件里怎么实现、恶心了半天。
最后还是回头用去 .Net 自带 System.Net.Mail 去实现
方法:
/// <summary> /// 发送邮件 /// </summary> /// <param name="StrTo">收件人Email</param> /// <param name="StrBody">邮件内容</param> /// <param name="strSubjec">邮件标题</param> public void SendMail(string StrTo, string StrBody, string strSubjec) { MailMessage onemail = new MailMessage(); string myEmail = "****@gmail.com"; //发送邮件的邮箱地址 string myPwd = "用户密码"; //发送邮件的邮箱密码 onemail.BodyEncoding = System.Text.Encoding.UTF8; onemail.IsBodyHtml = true; onemail.From = new MailAddress(myEmail); onemail.To.Add(new MailAddress(StrTo)); onemail.Subject = strSubjec; onemail.Body = StrBody; SmtpClient clint = new SmtpClient("smtp.gmail.com", 587);//发送邮件的服务器 clint.Credentials = new System.Net.NetworkCredential(myEmail, myPwd); clint.EnableSsl = true; clint.Timeout = 15000; try { clint.Send(onemail); } catch (Exception ex) { Response.Write(ex.Message); } } /// <summary> /// 发送邮件 /// </summary> public void SendGmail() { string to = "43100678@qq.com"; string from = "****@gmail.com"; string subject = "测试"; string body = "测试内容"; MailMessage message = new MailMessage(from, to, subject, body); //SmtpClient client = new SmtpClient("smtp.gmail.com", 465); SmtpClient client = new SmtpClient("smtp.gmail.com", 587); client.Credentials = new NetworkCredential("****@gmail.com", "用户密码"); client.EnableSsl = true; client.Send(message); }
其他:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.Mail; using DidaAsynchronousQueue.Model; using DidaAsynchronousQueue.DataAccess; using System.IO; namespace DidaAsynchronousQueue.Logic { /// <summary> /// 发送Mail /// </summary> public class SendMail : Queue { public SendMail() { } #region 外部设置 private bool enableSsl = Convert.ToBoolean(SQLTEXT.GetString("EnableSsl")); /// <summary> /// 是否加密 /// </summary> public bool EnableSsl { get { return enableSsl; } set { enableSsl = value; } } private string senderMail = SQLTEXT.GetString("SenderMail"); /// <summary> /// 发件人邮箱 /// </summary> public string SenderMail { get { return senderMail; } set { senderMail = value; } } private string senderPwd = SQLTEXT.GetString("SenderPwd"); /// <summary> /// 发件人密码 /// </summary> public string SenderPwd { get { return senderPwd; } set { senderPwd = value; } } private string host = SQLTEXT.GetString("Host"); /// <summary> /// STMP服务器地址 /// </summary> public string Host { get { return host; } set { host = value; } } private int port = Convert.ToInt32(SQLTEXT.GetString("Port")); /// <summary> /// 端口号 /// </summary> public int Port { get { return port; } set { port = value; } } private bool isBodyHtml = Convert.ToBoolean(SQLTEXT.GetString("IsBodyHtml")); /// <summary> /// 是否Html内容邮件 /// </summary> public bool IsBodyHtml { get { return isBodyHtml; } set { isBodyHtml = value; } } /// <summary> /// 邮件内容编码格式 /// </summary> public Encoding BodyEncoding { get { Encoding ed = Encoding.Default; switch (SQLTEXT.GetString("BodyEncoding").ToUpper()) { case "ASCII": ed = Encoding.ASCII; break; case "UNICODE": ed = Encoding.Unicode; break; case "UTF32": ed = Encoding.UTF32; break; case "UTF7": ed = Encoding.UTF7; break; case "UTF8": ed = Encoding.UTF8; break; } return ed; } } #endregion //private bool isAttachment = false; ///// <summary> ///// 是否包含附件 ///// </summary> //public bool IsAttachment { get { return isAttachment; } set { isAttachment = value; } } /// <summary> /// 收件人集合 /// </summary> public string ToMails = ""; //public List<string> ToMails { get; set; } /// <summary> /// 抄送收件人集合 /// </summary> public string CC = ""; //public List<string> CC { get; set; } /// <summary> /// 密送收件人集合 /// </summary> public string Bcc = ""; //public List<string> Bcc { get; set; } /// <summary> /// 发件人名称 /// </summary> private string SenderName { get; set; } private MailPriority priority = MailPriority.Normal; /// <summary> /// 优先级 /// </summary> public MailPriority Priority { get { return priority; } set { priority = value; } } /// <summary> /// 邮件主题 /// </summary> public string Subject { get; set; } /// <summary> /// 邮件内容 /// </summary> public string Body { get; set; } /// <summary> /// 附件集合 /// </summary> public string AttachmentList = ""; //public List<string> AttachmentList { get; set; } private DeliveryNotificationOptions dNOption = DeliveryNotificationOptions.OnFailure; /// <summary> /// Delay 通知传送是否延迟 Never 从不通知。 None 没有通知。 OnFailure 通知传送是否失败。 OnSuccess 通知传送是否成功。 /// </summary> public DeliveryNotificationOptions DNOption { get { return dNOption; } set { dNOption = value; } } /// <summary> /// 执行任务 /// </summary> public override void DoProcess(Object obj) { #region 读取 QueueModel qm = obj as QueueModel; EmailDA em = new EmailDA(); SetMail(em.QueryEmailbyTaskId(qm.AutoId).EMailPath); #endregion SmtpClient smtp = new SmtpClient(); //发送邮件的方式 smtp.DeliveryMethod = SmtpDeliveryMethod.Network; //指定邮件服务器 smtp.Host = Host; //Gmail QQ stmp ssl加密使用的端口 smtp.Port = Port; //经过ssl加密 smtp.EnableSsl = EnableSsl; //验证发件人的身份 用户名(邮件地址和密码) smtp.Credentials = new System.Net.NetworkCredential(SenderMail, SenderPwd); //初始化信息(来自 接收人) MailMessage _mailmessage = new MailMessage(SenderMail, ToMails); #region 抄送,密送 //抄送送多个人 接收人邮件地址以,隔开 if (!string.IsNullOrEmpty(CC)) { //添加多个收件人 群发 _mailmessage.CC.Add(CC); } //密送送多个人 接收人邮件地址以,隔开 if (!string.IsNullOrEmpty(Bcc)) { //添加多个收件人 群发 _mailmessage.Bcc.Add(Bcc); } #endregion //如果发送失败,SMTP 服务器将发送 失败邮件通知 _mailmessage.DeliveryNotificationOptions = DNOption; //优先级 _mailmessage.Priority = Priority; //发送主题 _mailmessage.Subject = Subject; //string cid = ""; //有附件则添加附件 if (!string.IsNullOrEmpty(AttachmentList)) { string[] attc = AttachmentList.Split(','); for (int i = 0; i < attc.Length; i++) { string mName = attc[i].ToLower(); mName = mName.Substring(mName.LastIndexOf("//") + 1); if (attc[i].ToLower().IndexOf("LOGO") > -1) { //添加附件 System.Net.Mail.Attachment attch = new System.Net.Mail.Attachment(attc[i]); attch.Name = System.IO.Path.GetFileName(attc[i]); attch.NameEncoding = System.Text.Encoding.GetEncoding("gb2312"); attch.TransferEncoding = System.Net.Mime.TransferEncoding.Base64; attch.ContentDisposition.Inline = true; attch.ContentDisposition.DispositionType = System.Net.Mime.DispositionTypeNames.Inline; attch.ContentId = mName;//关键性的地方,这里得到一个id数值 _mailmessage.Attachments.Add(attch); } else { System.Net.Mail.Attachment attch = new System.Net.Mail.Attachment(attc[i]); _mailmessage.Attachments.Add(attch); } } } //邮件主题编码 _mailmessage.SubjectEncoding = BodyEncoding; //指定发送的格式 (Html) _mailmessage.IsBodyHtml = IsBodyHtml; //指定发送邮件的编码 _mailmessage.BodyEncoding = BodyEncoding; //指定邮件内容 _mailmessage.Body = Body; //发送邮件 try { Log.append("Mail正在发送...!"); smtp.Send(_mailmessage); //记录日志 Log.append("发送给【" + ToMails + "】的邮件,成功!"); } catch (Exception ex) { //记录日志 , 修改重试次数 throw new Exception("发送给【" + ToMails + "】的邮件,失败!异常原因:" + ex.Message); } } private void SetMail(string path) { StreamReader ts = new StreamReader(System.IO.Path.GetFullPath(path), BodyEncoding); //收件人 string to = ts.ReadLine(); ToMails = to.Substring(4, to.Length - 5); //抄送人 string cc = ts.ReadLine(); CC = cc.Substring(4, cc.Length - 5); //密送人 string bcc = ts.ReadLine(); Bcc = bcc.Substring(5, bcc.Length - 6); //主题 string subject = ts.ReadLine(); Subject = subject.Substring(9, subject.Length - 10); string body = ts.ReadLine(); StreamReader srbody = new StreamReader(System.IO.Path.GetFullPath(body.Substring(6, body.Length - 7)), BodyEncoding); Body = srbody.ReadToEnd(); srbody.Close(); srbody = null; //附件 string attach = ts.ReadLine(); if (attach.Length > 13) { //附件 AttachmentList = attach.Substring(12, attach.Length - 13); } ts.Close(); ts = null; } #region 处理集合,返回字符串 private string GetString(List<string> ToMails) { StringBuilder toStr = new StringBuilder(); if (ToMails != null) { foreach (string s in ToMails) { toStr.Append(s + ","); } } return toStr.ToString().TrimEnd(','); } #endregion } }
配置文件:
<?xml version="1.0"?> <configuration> <appSettings> <!--数据库连接字符串--> <add key="SqlConnectionString" value="Data Source=.;Initial Catalog=;User ID=sa;Password="/> <add key="SendMail" value="true"/> <add key="MakeMail" value="true"/> <add key="MakePDF" value="true"/> </appSettings> <connectionStrings> <!--发件人mail--> <add name="SenderMail" connectionString="d.east6@gmail.com" /> <!--发件人mail--> <add name="SenderPwd" connectionString="" /> <!--发件人密码--> <add name="EnableSsl" connectionString="true" /> <!--stmp服务器地址--> <add name="Host" connectionString="smtp.gmail.com" /> <!--端口号--> <add name="Port" connectionString="587" /> <!--是否Html内容邮件--> <add name="IsBodyHtml" connectionString="true" /> <!--邮件内容编码格式[ASCII][Unicode][UTF32][UTF7][UTF8][Default],空则为默认Default编码格式--> <add name="BodyEncoding" connectionString="" /> <!--Timer控件的间隔,1000为1秒--> <add name="Sleep" connectionString="1000" /> </connectionStrings> </configuration>