/// <summary> /// 获取SMTP Client实例 /// </summary> /// <param name="server"></param> /// <param name="port"></param> /// <returns></returns> private SmtpClient GetSmtpClient(string server, int port) { //构造SMTP的连接器 SmtpClient smtp = new SmtpClient(server, port); if (!string.IsNullOrEmpty(this.HostName)) { FieldInfo field = smtp.GetType().GetField("localHostName", BindingFlags.Instance | BindingFlags.NonPublic); if (field != null) { field.SetValue(smtp, this.HostName); } } //超时设置 smtp.Timeout = this.Server.Timeout; if (this.Server.EnableAuth) { //设置凭据 NetworkCredential credential = new NetworkCredential(this.Server.UserName, this.Server.Password); if (this.Server.EnableSsl) { //SSL验证 smtp.Credentials = credential; smtp.EnableSsl = this.Server.EnableSsl; } else { //普通验证 smtp.Credentials = credential.GetCredential(server, port, this.Server.AuthenticationType); } } return(smtp); }
public async Task sendEmail(string emailAddress, string title, string message) { try { var mailHtml = File.ReadAllText("HtmlTemplates/mail.html").Replace("${message}", message); using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(mailHtml))) { MailMessage mail = new MailMessage(new MailAddress("*****@*****.**", "Idea Stok Takip", Encoding.UTF8), new MailAddress(emailAddress)); mail.Subject = title; mail.Body = message; mail.IsBodyHtml = true; mail.BodyEncoding = Encoding.UTF8; mail.HeadersEncoding = Encoding.UTF8; mail.SubjectEncoding = Encoding.UTF8; mail.Body = mailHtml; SmtpClient mailClient = new SmtpClient("mail.trabzon.bel.tr");// Bilinmiyor mailClient.Port = 587; mailClient.UseDefaultCredentials = false; mailClient.Credentials = new NetworkCredential("*****@*****.**", "1Qaz2wsx*");// Şifre bilinmiyor mailClient.EnableSsl = false; var transportProp = mailClient.GetType().GetField("_transport", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); var transport = transportProp.GetValue(mailClient); var authModulesProp = transport.GetType() .GetField("_authenticationModules", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); var authModules = authModulesProp.GetValue(transport) as Array; var activemodule = authModules.GetValue(authModules.Length - 1); var newModules = Array.CreateInstance(activemodule.GetType(), 1); newModules.SetValue(activemodule, 0); authModulesProp.SetValue(transport, newModules); mailClient.Send(mail); await Task.CompletedTask; } } catch (Exception e) { } }
public static void ForceSmtpAuthentication(this SmtpClient smtpClient, SmtpAuthentication smtpAuthentication) { var transport = smtpClient.GetType().GetField("transport", BindingFlags.NonPublic | BindingFlags.Instance); if (transport != null) { var authenticationModules = transport.GetValue(smtpClient).GetType().GetField("authenticationModules", BindingFlags.NonPublic | BindingFlags.Instance); if (authenticationModules != null) { var modulesArray = authenticationModules.GetValue(transport.GetValue(smtpClient)) as Array; if (modulesArray != null) { var smtpAuthenticationModule = modulesArray.GetValue((byte)smtpAuthentication); modulesArray.SetValue(smtpAuthenticationModule, 0); modulesArray.SetValue(smtpAuthenticationModule, 1); modulesArray.SetValue(smtpAuthenticationModule, 2); modulesArray.SetValue(smtpAuthenticationModule, 3); } } } }
/// <summary> /// 发送邮件 /// </summary> public Result Send(string title, string content, bool isHtml = true) { var rtv = new Result(); if (String.IsNullOrEmpty(SmtpHost)) { rtv.error("必须提供发送邮件的smtp地址"); return(rtv); } if (_ToEmails.Count == 0) { rtv.error("需要设置发送到的邮件地址"); return(rtv); } MailMessage msg = null; var smtp = new SmtpClient(); //SmtpConnection Hello 乱发名字 try { var attr = smtp.GetType().GetField("clientDomain", Monitor.AllFlag); attr.SetValue(smtp, ClientName); } catch (Exception e) { rtv.fail("无法设置客户端名称:" + e.Message, e.ToString()); return(rtv); } try { int dataLen; var msgRes = BuildMessage(title, content, out dataLen, isHtml); if (msgRes.IsError) { msgRes.errorTo(rtv); return(rtv); } msg = msgRes.Value; var timeout = TimeoutMillisecond; if (timeout == defaultTimeout) { //重新计算超时时间 timeout = Math.Max((dataLen / (50 * 1024)) * 1000, defaultTimeout); } while (_DKIM != null) { if (dataLen > DKIM_MaxLen) { break; } var res = _DKIM.Sign(msg); if (res.IsError) { res.errorTo(rtv); return(rtv); } break; } smtp.Host = SmtpHost; smtp.Port = SmtpPort; smtp.EnableSsl = SmtpSSL; if (!String.IsNullOrEmpty(User)) { smtp.Credentials = new NetworkCredential(User, Password); } smtp.Timeout = timeout; if (OnSendBefore != null) { if (!OnSendBefore(smtp)) { rtv.error("邮件发送前被取消"); return(rtv); } } var task = smtp.SendMailAsync(msg); var isout = !task.Wait(timeout); if (isout || task.Exception != null) { smtp.SendAsyncCancel(); if (isout) { rtv.error("邮件发送超时"); return(rtv); } throw task.Exception; } return(rtv); } catch (AggregateException ex) { var e = ex.InnerException; rtv.fail("邮件发送出错:" + e.Message, e.ToString()); return(rtv); } catch (Exception e) { rtv.fail("邮件发送异常:" + e.Message, e.ToString()); return(rtv); } finally { if (msg != null) { msg.Dispose(); } if (smtp != null) { smtp.Dispose(); } } }
/// <summary> /// 发送邮件 /// </summary> public Result Send(string title, string content, bool isHtml = true) { var rtv = new Result(); if (_ToEmails.Count == 0) { rtv.error("需要设置发送到的邮件地址"); return(rtv); } if (String.IsNullOrEmpty(SmtpHost) && _ToEmails.Count != 1) { rtv.error("不提供smtp地址时只能提供一个收件地址"); return(rtv); } MailMessage msg = null; var smtp = new SmtpClient(); //SmtpConnection Hello 乱发名字 try { var attr = smtp.GetType().GetField("clientDomain", Monitor.AllFlag); attr.SetValue(smtp, ClientName); } catch (Exception e) { rtv.fail("无法设置客户端名称:" + e.Message, e.ToString()); return(rtv); } try { int dataLen; var msgRes = BuildMessage(title, content, out dataLen, isHtml); if (msgRes.IsError) { msgRes.errorTo(rtv); return(rtv); } msg = msgRes.Value; var timeout = TimeoutMillisecond; if (timeout == defaultTimeout) { //重新计算超时时间 timeout = Math.Max((dataLen / (50 * 1024)) * 1000, defaultTimeout); } while (_DKIM != null) { if (dataLen > DKIM_MaxLen) { break; } var res = _DKIM.Sign(msg); if (res.IsError) { res.errorTo(rtv); return(rtv); } break; } if (String.IsNullOrEmpty(SmtpHost)) { var hostRes = new DNS_MX().QueryOne(msg.To[0].Host); if (hostRes.IsError) { hostRes.errorTo(rtv, "发送邮件失败:无法解析收件服务器"); return(rtv); } SmtpHost = hostRes.Value; } smtp.Host = SmtpHost; smtp.Port = SmtpPort; smtp.EnableSsl = SmtpSSL; if (!String.IsNullOrEmpty(User)) { smtp.Credentials = new NetworkCredential(User, Password); } smtp.Timeout = timeout; //统一用7位,不然不支持的服务器没法统一进行签名 smtp.DeliveryFormat = SmtpDeliveryFormat.SevenBit; if (OnSendBefore != null) { if (!OnSendBefore(msg, smtp)) { rtv.error("邮件发送前被取消"); return(rtv); } } //不能用异步方法,.Net SendAsync方法有bug,本应通过IsUnicodeSupported=ServerSupportsEai&&DeliveryFormat来判断是否支持utf-8,然而异步方法手贱直接用ServerSupportsEai来判断,导致DeliveryFormat无法控制编码方式!!表现为:支持SMTPUTF8的服务器100%不编码,不支持的100%编码。 smtp.Send(msg); return(rtv); } catch (AggregateException ex) { var e = ex.InnerException; rtv.fail("邮件发送出错:" + e.Message, e.ToString()); return(rtv); } catch (Exception e) { rtv.fail("邮件发送异常:" + e.Message, e.ToString()); return(rtv); } finally { if (msg != null) { msg.Dispose(); } if (smtp != null) { smtp.Dispose(); } } }