public void SendMail(DataTable dtParam, string asFromMail, string asToMail, string sTitle, string asFileName) { System.Web.Mail.MailMessage mail = new System.Web.Mail.MailMessage(); string sFilePath = GetAppConfig("Mail.Template") + asFileName; string sContent = ""; sContent = GetMailContent(asFileName, dtParam); mail.From = asFromMail; mail.To = asToMail; mail.Subject = sTitle; mail.Body = sContent; mail.BodyFormat = System.Web.Mail.MailFormat.Html; mail.BodyEncoding = System.Text.Encoding.Default; System.Web.Mail.SmtpMail.SmtpServer = GetAppConfig("Mail.SMTP"); try { System.Web.Mail.SmtpMail.Send(mail); } catch { } }
/// <summary> /// 发送邮件 /// </summary> /// <param name="mess">消息</param> /// <returns>发送是否完成</returns> public void SendMailWeb(System.Web.Mail.MailMessage mailmsg) { //sender here mailmsg.From = accountName; // certify needed mailmsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");//1 is to certify //the user id mailmsg.Fields.Add( "http://schemas.microsoft.com/cdo/configuration/sendusername", accountName); //the password mailmsg.Fields.Add( "http://schemas.microsoft.com/cdo/configuration/sendpassword", _password); System.Web.Mail.SmtpMail.SmtpServer = _smtpServer; try { System.Web.Mail.SmtpMail.Send(mailmsg); } catch (Exception ee) { System.Console.WriteLine(ee.Message); } }
public void SendMail(string[,] asaInfo, string asFromMail, string asToMail, BSC_SendMailType enType) { System.Web.Mail.MailMessage mail = new System.Web.Mail.MailMessage(); string sSubTitle = ""; string sContent = ""; sContent = GetMailContent(asaInfo, enType, out sSubTitle); mail.From = GetAppConfig("Mail.From"); mail.To = asToMail; mail.Subject = sSubTitle; mail.Body = sContent; mail.BodyFormat = System.Web.Mail.MailFormat.Html; mail.BodyEncoding = System.Text.Encoding.Default; System.Web.Mail.SmtpMail.SmtpServer = GetAppConfig("Mail.SMTP"); try { System.Web.Mail.SmtpMail.Send(mail); } catch {} }
public static bool SendEmail(string toemail, string title, string body) { try { System.Web.Mail.MailMessage mail = new System.Web.Mail.MailMessage(); mail.From = "*****@*****.**"; mail.To = toemail; mail.Subject = title; mail.Priority = System.Web.Mail.MailPriority.High; mail.Body = body; mail.BodyFormat = System.Web.Mail.MailFormat.Html; mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); //用户名 mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "*****@*****.**"); //密码 mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "wx123456"); //SMTP地址 System.Web.Mail.SmtpMail.SmtpServer = "smtp.163.com"; //开始发送邮件 System.Web.Mail.SmtpMail.Send(mail); return(true); } catch { return(false); } }
/// <summary> /// 发送邮件 /// </summary> /// <returns>true:发送成功,flase:发送失败</returns> public bool SendEmail() { //创建MailMessage对象 System.Web.Mail.MailMessage mailMsg = new System.Web.Mail.MailMessage(); //设置收件人的邮件地址 mailMsg.To = _ToEmail; //设置发送者的邮件地址 mailMsg.From = _FromEmail; //设置邮件主题 mailMsg.Subject = _EmailSubject; //设置邮件内容 mailMsg.Body = _EmailBody; //设置支持服务器验证 if (_IsAuth == true) { mailMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); //设置用户名 mailMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", _EmailUserName); //设置用户密码 mailMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", _EmailPassword); } try { //设置发送邮件服务器 System.Web.Mail.SmtpMail.SmtpServer = _SmtpServer; //发送邮件 System.Web.Mail.SmtpMail.Send(mailMsg); return(true); } catch { return(false); } }
/// <summary> /// 发送电子邮件。 /// </summary> /// <returns>是否发送成功。</returns> public bool Send2() { //初始化 MailMessage 对象。 System.Web.Mail.MailMessage mail = new System.Web.Mail.MailMessage(); Encoding encoding = Encoding.GetEncoding("utf-8"); mail.From = From; ////mail.To.Add(new MailAddress(this.Recipient, this.RecipientName)); //this.Recipients.ForEach(r => //{ // mail.To.Add(new MailAddress(r.Recipient, r.RecipientName)); //}); mail.To = Recipients[0].Recipient; mail.Subject = this.Subject; mail.BodyFormat = this.IsBodyHtml ? System.Web.Mail.MailFormat.Html : System.Web.Mail.MailFormat.Text; mail.Body = this.Body; mail.Priority = System.Web.Mail.MailPriority.Normal; mail.BodyEncoding = encoding; if (this.Attachment.Count > 0) { foreach (string file in this.Attachment) { mail.Attachments.Add(new Attachment(file)); } } #region 注释 //初始化 SmtpClient 对象。 //SmtpClient smtp = new SmtpClient(); //smtp.Host = this.ServerHost; //smtp.Port = this.ServerPort; //smtp.UseDefaultCredentials = true; //smtp.Credentials = new NetworkCredential(this.Username, this.Password); //mail.Headers.Add("X-Priority", "3"); //mail.Headers.Add("X-MSMail-Priority", "Normal"); //mail.Headers.Add("X-Mailer", "Microsoft Outlook Express 6.00.2900.2869"); //mail.Headers.Add("X-MimeOLE", "Produced By Microsoft MimeOLE v6.00.2900.2869"); //mail.Headers.Add("ReturnReceipt", "1"); #endregion mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); //用户名 mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", Username); //密码 mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", Password); //端口 mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", ServerPort); //是否ssl mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true"); System.Web.Mail.SmtpMail.SmtpServer = ServerHost; try { System.Web.Mail.SmtpMail.Send(mail); } catch (SmtpException ex) { string message = ex.Message; return(false); } return(true); }
/// <summary> /// 发送EMAIL /// </summary> /// <example> /// <code> /// Email _Email = new Email(); /// _Email.FromEmail = "*****@*****.**"; /// _Email.Subject = "<div>aaaa</div>"; /// _Email.Body = "aaaaaaaaaaaaa"; /// _Email.SmtpServer = "smtp.163.com"; /// _Email.SmtpUserName = "******"; /// _Email.SmtpPassword = "******"; /// _Email.Send("*****@*****.**"); /// </code> /// </example> /// <param name="toEmail">收信人 接收方地址</param> /// <returns>成功否</returns> public bool SmtpMailSend(string toEmail) { lock (lockHelper) { System.Web.Mail.MailMessage msg = new System.Web.Mail.MailMessage(); try { msg.From = _FromEmail; //发送方地址(如[email protected]) msg.To = toEmail; //接收方地址 msg.BodyFormat = _Format; //正文内容类型 msg.BodyEncoding = _Encoding; //正文内容编码 msg.Subject = _Subject; //主题 msg.Body = _Body; //内容 msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); //设置为需要用户验证 if (!_SmtpPort.Equals("25")) { msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", _SmtpPort); //设置端口 } msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", _SmtpUserName); //设置验证用户名 msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", _SmtpPassword); //设置验证密码 System.Web.Mail.SmtpMail.SmtpServer = _SmtpServer; //邮件服务器地址(如smtp.163.com) System.Web.Mail.SmtpMail.Send(msg); //发送 return(true); } catch { } finally { } } return(false); }
public void SendMail() { string pGmailEmail = "*****@*****.**"; string pGmailPassword = "******"; string pTo = "ToAddress"; //[email protected] string pSubject = "Test From Gmail"; string pBody = "Body"; //Body MailFormat pFormat = MailFormat.Text; //Text Message string pAttachmentPath = string.Empty; //No Attachments System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage(); myMail.Fields.Add ("http://schemas.microsoft.com/cdo/configuration/smtpserver", "smtp.gmail.com"); myMail.Fields.Add ("http://schemas.microsoft.com/cdo/configuration/smtpserverport", "465"); myMail.Fields.Add ("http://schemas.microsoft.com/cdo/configuration/sendusing", "2"); //sendusing: cdoSendUsingPort, value 2, for sending the message using //the network. //smtpauthenticate: Specifies the mechanism used when authenticating //to an SMTP //service over the network. Possible values are: //- cdoAnonymous, value 0. Do not authenticate. //- cdoBasic, value 1. Use basic clear-text authentication. //When using this option you have to provide the user name and password //through the sendusername and sendpassword fields. //- cdoNTLM, value 2. The current process security context is used to // authenticate with the service. myMail.Fields.Add ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); //Use 0 for anonymous myMail.Fields.Add ("http://schemas.microsoft.com/cdo/configuration/sendusername", pGmailEmail); myMail.Fields.Add ("http://schemas.microsoft.com/cdo/configuration/sendpassword", pGmailPassword); myMail.Fields.Add ("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true"); myMail.From = pGmailEmail; myMail.To = pTo; myMail.Subject = pSubject; myMail.BodyFormat = pFormat; myMail.Body = pBody; if (pAttachmentPath.Trim() != "") { MailAttachment MyAttachment = new MailAttachment(pAttachmentPath); myMail.Attachments.Add(MyAttachment); myMail.Priority = System.Web.Mail.MailPriority.High; } SmtpMail.SmtpServer = "smtp.gmail.com:465"; SmtpMail.Send(myMail); }
/// <summary> /// 发送邮件 /// </summary> /// <param name="to">接收邮件</param> /// <param name="subject">邮件标题</param> /// <param name="body">邮件内容</param> /// <returns>是否发送成功</returns> public bool Send(string to, string subject, string body) { System.Web.Mail.MailMessage mail = new System.Web.Mail.MailMessage(); try { mail.To = to; mail.From = _from; mail.Subject = subject; mail.BodyFormat = System.Web.Mail.MailFormat.Html; mail.Body = body; mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); //basic authentication mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", _username); //set your username here mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", _password); //set your password here mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", _port); //set port mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", _port != 25?"true":"false"); //set is ssl System.Web.Mail.SmtpMail.SmtpServer = _host; BSPLog.Instance.Write(string.Format("发送邮件:{0}:{1}", _host, _port)); System.Web.Mail.SmtpMail.Send(mail); BSPLog.Instance.Write("邮件发送成功"); return(true); } catch (Exception Ex) { BSPLog.Instance.Write("发送邮件时出错:" + Ex.Message); return(false); } }
static public void SendMail(pages.ForumPage basePage, string from, string fromName, string to, string toName, string subject, string body) { if (toName != null && toName.Length > 0) { to = "\"" + toName + "\" <" + to + ">"; } if (fromName != null && fromName.Length > 0) { from = "\"" + fromName + "\" <" + from + ">"; } System.Web.Mail.MailMessage Mail = new System.Web.Mail.MailMessage(); Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"] = basePage.BoardSettings.SmtpServer; Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"] = 25; Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"] = 2; if (basePage.BoardSettings.SmtpUserName != null && basePage.BoardSettings.SmtpUserPass != null) { Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1; Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] = basePage.BoardSettings.SmtpUserName; Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = basePage.BoardSettings.SmtpUserPass; } Mail.To = to; Mail.From = from; Mail.Subject = subject; Mail.Body = body; System.Web.Mail.SmtpMail.SmtpServer = basePage.BoardSettings.SmtpServer; System.Web.Mail.SmtpMail.Send(Mail); }
public static bool SendMail(string strFrom, string strTo, string strCc, string strSubject, string strBody) { System.Web.Mail.MailMessage objMailMessage = new System.Web.Mail.MailMessage(); objMailMessage.From = strFrom; objMailMessage.To = strTo; objMailMessage.Cc = strCc; objMailMessage.Subject = strSubject; objMailMessage.BodyFormat = System.Web.Mail.MailFormat.Text; objMailMessage.Priority = System.Web.Mail.MailPriority.High; objMailMessage.Body = strBody; try { objMailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); objMailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "*****@*****.**"); objMailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "SENHA"); System.Web.Mail.SmtpMail.SmtpServer = "pop.visioncom.com.br"; System.Web.Mail.SmtpMail.Send(objMailMessage); return(true); } catch { return(false); } }
protected void _btnSend_Click(object sender, EventArgs e) { // show what happened _lblErr.Visible = true; try { // create report file string fileName = Page.MapPath("report.rtf"); _c1wr.Report.RenderToFile(fileName, C1.C1Report.FileFormatEnum.RTF); // create message System.Web.Mail.MailMessage mm = new System.Web.Mail.MailMessage(); mm.Subject = "Sales Goal Report"; mm.From = "*****@*****.**"; // << must be a valid email mm.To = "*****@*****.**"; mm.Body = "Hi Joe. I got the sales goal down. Here's the final report."; // attach System.Web.Mail.MailAttachment att = new System.Web.Mail.MailAttachment(fileName); mm.Attachments.Add(att); // and send... System.Web.Mail.SmtpMail.Send(mm); _lblErr.Text = "** Your report is in the mail!"; } catch (Exception x) { _lblErr.Text = "Sorry, failed to send because<br>" + x.Message; _lblErr.BackColor = Color.Pink; } }
public static bool send(string mailto, string subject, string content, string fileAttach) { System.Web.Mail.MailMessage oMessage = new System.Web.Mail.MailMessage(); oMessage.To = mailto; oMessage.From = "*****@*****.**"; oMessage.Subject = subject; oMessage.Body = content; oMessage.BodyEncoding = System.Text.Encoding.UTF8; oMessage.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"] = 2; oMessage.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"] = "tuanbm"; //dinh kem System.Web.Mail.MailAttachment myAttachment = new System.Web.Mail.MailAttachment(fileAttach, System.Web.Mail.MailEncoding.Base64); oMessage.Attachments.Add(myAttachment); //tren server System.Web.Mail.SmtpMail.SmtpServer = "tuanbm"; //dinh dang //oMessage.BodyFormat = System.Web.Mail.MailFormat.Html; try { System.Web.Mail.SmtpMail.Send(oMessage); //Console.Write(" Gui email thanh cong : "); return(true); } catch (Exception Ex) { //Console.Write(" Loi : " + Ex); return(false); } }
#pragma warning disable 0618 public System.Web.Mail.MailMessage ToWebMessage() { var message = new System.Web.Mail.MailMessage() { From = _from, Body = Body, Subject = Subject, To = semiColonJoinAddress(To), Cc = semiColonJoinAddress(_cc), Bcc = semiColonJoinAddress(_bcc), BodyFormat = _htmlBody ? System.Web.Mail.MailFormat.Html : System.Web.Mail.MailFormat.Text, }; foreach (String readReceipt in _readNotificationAddresses ?? new List <String>()) { message.Headers.Add("Disposition-Notification-To", readReceipt); } foreach (String att in _attachments ?? new List <String>()) { message.Attachments.Add(new System.Web.Mail.MailAttachment(Path.GetFullPath(att))); } return(message); }
private System.Web.Mail.MailMessage BuildMessage(string reworkCode, string mUser, int mdate, int mtime) { BenQGuru.eMES.BaseSetting.UserFacade userFacade = new BenQGuru.eMES.BaseSetting.UserFacade(_domainDataProvider); object user = userFacade.GetUser(mUser); System.Web.Mail.MailMessage message = new System.Web.Mail.MailMessage(); message.Subject = string.Format("返工需求单({0}),待签核:", reworkCode); message.Priority = System.Web.Mail.MailPriority.High; message.Body = string.Format(@" <html> <table> <tr> <td>您好! </td> </tr> <tr align=right><td> 新增返工需求单 ({0}), 待签核。</td> </tr> <tr align=right><td> {1}</td> </tr> <tr align=right><td> {2}</td> </tr> <tr align=right><td> {3}</td> </tr> </table> </html>", reworkCode, mUser, (user as BenQGuru.eMES.Domain.BaseSetting.User).UserTelephone, FormatHelper.TODateTimeString(mdate, mtime, "-", ":")); return(message); }
public void SendEmail(string title, string body, string mailTo) { string Smtp = ConfigurationManager.AppSettings["Smtp"].ToString(); string Port = ConfigurationManager.AppSettings["Port"].ToString(); string MailFrom = ConfigurationManager.AppSettings["MailFrom"].ToString(); string MailPwd = ConfigurationManager.AppSettings["MailPwd"].ToString(); System.Web.Mail.MailMessage mail = new System.Web.Mail.MailMessage(); try { mail.From = MailFrom; mail.To = mailTo; mail.Subject = title; mail.BodyFormat = System.Web.Mail.MailFormat.Html; mail.Body = body; mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); //basic authentication mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", MailFrom); //set your username here mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", MailPwd); //set your password here mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", Port); //set port mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true"); //set is ssl System.Web.Mail.SmtpMail.SmtpServer = Smtp; System.Web.Mail.SmtpMail.Send(mail); } catch (Exception ex) { _logger.ErrorFormat("发送邮件异常:" + ex.Message); } }
public static void SendEmail(FolderMapContainer container) { string From = System.Configuration.ConfigurationSettings.AppSettings["EmailFrom"]; string Body = ""; if( container.BODY.Length > 0 ) { Body = container.BODY; } else { Body = System.Configuration.ConfigurationSettings.AppSettings["EmailBody"] ; } string Subject = ""; if( container.SUBJECT.Length > 0 ) { Subject = container.SUBJECT; } else { Subject = System.Configuration.ConfigurationSettings.AppSettings["EmailSubject"]; } string SMTPServerName = System.Configuration.ConfigurationSettings.AppSettings["SMTPServerName"]; string Username = System.Configuration.ConfigurationSettings.AppSettings["Username"]; string Password = System.Configuration.ConfigurationSettings.AppSettings["Password"]; string[] emails = new string[5]; emails[0] = container.EMAIL1; emails[1] = container.EMAIL2; emails[2] = container.EMAIL3; emails[3] = container.EMAIL4; emails[4] = container.EMAIL5; foreach( string email in emails) { try { if( email.Length > 0 ) { System.Web.Mail.MailMessage mmsg = new System.Web.Mail.MailMessage(); mmsg.From = From; mmsg.To = email; mmsg.Body = Body; mmsg.Subject = Subject; System.Web.Mail.SmtpMail.SmtpServer = SMTPServerName;//"smtp.1and1.com"; mmsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); //basic authentication mmsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", Username); //set your username here mmsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", Password); //set your password here System.Web.Mail.SmtpMail.Send(mmsg); } } catch (Exception) { IReporter reporter = ReporterManager.GetReporter(); reporter.AddReport( new ActionReportContainer( ActionType.Notify, ActionReportResult.Failed, "Email notification to " + email + " failed")); } } }
private void configureMessageForChannelSecurity(System.Web.Mail.MailMessage message) { message.Fields.Add(HOST, _server); message.Fields.Add(PORT, _port); message.Fields.Add(SSL, "true"); message.Fields.Add(AUTH, "1"); // Use basic clear-text authentication. message.Fields.Add(USERNAME, _username); message.Fields.Add(PASSWORD, _password); message.Fields.Add(TIMEOUT, 90); }
public static void prueba1() { System.Web.Mail.MailMessage mail = new System.Web.Mail.MailMessage(); mail.From = "*****@*****.**"; mail.To = "*****@*****.**"; mail.Subject = "Prueba"; mail.Body = "Hola luuuuuu"; SmtpDirect.Send(mail); }
public ActionResult SendMailQT(string To, string Msg, string Subject) { int sMsg = 0; try { commFunction oComm = new commFunction(); // oComm.Send_Mail("*****@*****.**", "sSubject", "sBody"); // oComm.Email_With_CCandBCC("", "", "", "", ""); const string SERVER2 = "relay-hosting.secureserver.net"; sMsg = 1; System.Web.Mail.MailMessage oMail2 = new System.Web.Mail.MailMessage(); oMail2.From = "*****@*****.**"; oMail2.To = "*****@*****.**"; oMail2.Subject = "Acknowledgement"; oMail2.BodyFormat = System.Web.Mail.MailFormat.Html; // enumeration oMail2.Priority = System.Web.Mail.MailPriority.High; // enumeration sMsg = 2; oMail2.Body = "sBody"; System.Web.Mail.SmtpMail.SmtpServer = SERVER2; System.Web.Mail.SmtpMail.Send(oMail2); oMail2 = null; sMsg = 3; //string from = "*****@*****.**"; //any valid GMail ID //using (MailMessage mail = new MailMessage(from, To)) //{ // mail.Subject =Subject ;// // mail.Body = Msg; // //if (fileUploader != null) // //{ // // string fileName = Path.GetFileName(fileUploader.FileName); // // mail.Attachments.Add(new Attachment(fileUploader.InputStream, fileName)); // //} // mail.IsBodyHtml = false; // SmtpClient smtp = new SmtpClient(); // smtp.Host = "50.62.22.144";// "smtp.digiclayinfotech.com"; // smtp.EnableSsl = true; // NetworkCredential networkCredential = new NetworkCredential(from, "ajay123"); // smtp.UseDefaultCredentials = true; // smtp.Credentials = networkCredential; // smtp.Port = 587; // smtp.Host = "50.62.22.144"; //"localhost"; // smtp.Send(mail); // ViewBag.Message = "Sent"; // // return View("Index", objModelMail); //} return(Json(sMsg, JsonRequestBehavior.AllowGet)); } catch (Exception ex) { return(Json("E_" + sMsg + "_" + ex.Message, JsonRequestBehavior.AllowGet)); } }
public bool SendEmail(string pSubject, string pBody, System.Web.Mail.MailFormat pFormat, string pAttachmentPath, string pEmailTo) { try { System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage(); myMail.Fields.Add ("http://schemas.microsoft.com/cdo/configuration/smtpserver", "smtp.gmail.com"); myMail.Fields.Add ("http://schemas.microsoft.com/cdo/configuration/smtpserverport", "465"); myMail.Fields.Add ("http://schemas.microsoft.com/cdo/configuration/sendusing", "2"); myMail.Fields.Add ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); //Use 0 for anonymous myMail.Fields.Add ("http://schemas.microsoft.com/cdo/configuration/sendusername", "*****@*****.**"); myMail.Fields.Add ("http://schemas.microsoft.com/cdo/configuration/sendpassword", "espl@notification"); myMail.Fields.Add ("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true"); myMail.From = "*****@*****.**";//[email protected] myMail.To = pEmailTo; //myMail.Cc = "*****@*****.**"; myMail.Subject = pSubject; myMail.BodyFormat = pFormat; myMail.Body = pBody; if (pAttachmentPath.Trim() != "") { System.Web.Mail.MailAttachment MyAttachment = new System.Web.Mail.MailAttachment(pAttachmentPath); myMail.Attachments.Add(MyAttachment); myMail.Priority = System.Web.Mail.MailPriority.High; } System.Web.Mail.SmtpMail.SmtpServer = "smtp.gmail.com:465"; System.Web.Mail.SmtpMail.Send(myMail); return(true); } catch (Exception ex) { // throw; return(false); } finally { //SendEMail(KeysGlobal.pGmailEmail, KeysGlobal.pTo, pSubject, pBody, pAttachmentPath); } }
private void btnSend_Click(object sender, System.EventArgs e) { //System.Web.Mail.SmtpMail.SmtpServer="localhost"; System.Web.Mail.MailMessage mm = new System.Web.Mail.MailMessage(); mm.From = this.From.Text; mm.To = this.Address.Text; mm.Subject = (this.Subject.Text == "")?"無題":this.Subject.Text; mm.Body = this.Body.Text; mm.BodyEncoding = System.Text.Encoding.GetEncoding("iso-2022-jp"); System.Web.Mail.SmtpMail.Send(mm); }
public string Send(Dictionary <string, object> Data, string Template) { string result = string.Empty; Template = GetMailBody(Data, Template); try { if (Convert.ToBoolean(ConfigurationManager.AppSettings["IS_SMTP"])) { System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage(); mailMessage.From = new MailAddress(SenderEmail, SenderName); mailMessage.To.Add(new MailAddress(ToEmail)); mailMessage.Subject = Subject; mailMessage.Body = Template; mailMessage.IsBodyHtml = true; mailMessage.BodyEncoding = System.Text.UnicodeEncoding.UTF8; if (CCEmail != null && CCEmail != "") { mailMessage.CC.Add(new MailAddress(CCEmail)); } System.Net.Mail.SmtpClient client = new SmtpClient(); client.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["SMTP_USER"], ConfigurationManager.AppSettings["SMTP_PASSWORD"]); client.Host = ConfigurationManager.AppSettings["SMTP_SERVER"];//"smtp.gmail.com"; client.Port = Convert.ToInt32(ConfigurationManager.AppSettings["SMTP_PORT"]); client.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["SMTP_SSL"]); client.Send(mailMessage); result = "1"; } else { System.Web.Mail.MailMessage mailMessage = new System.Web.Mail.MailMessage(); mailMessage.To = ToEmail; mailMessage.From = SenderEmail; if (CCEmail != null && CCEmail != "") { mailMessage.Cc = CCEmail; } mailMessage.Subject = Subject; mailMessage.Body = Template; mailMessage.Priority = System.Web.Mail.MailPriority.High; mailMessage.BodyFormat = System.Web.Mail.MailFormat.Html; mailMessage.BodyEncoding = System.Text.UnicodeEncoding.UTF8; System.Web.Mail.SmtpMail.Send(mailMessage); result = "okie"; } } catch (Exception ex) { Error = ex.Message; result = Error; } return(result); }
private static void SendWebMail(string sHost, int nPort, string sUserName, string sPassword, string sFromName, string sFromEmail, string sToEmail, string sHeader, string sMessage, bool fSSL) { try { if (sFromName == "") { sFromName = sFromEmail; } System.Web.Mail.MailMessage Mail = new System.Web.Mail.MailMessage(); Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"] = sHost; Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"] = 2; Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"] = nPort.ToString(); if (fSSL) { Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpusessl"] = "true"; } if (sUserName.Length == 0) { } else { Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1; Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] = sUserName; Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = sPassword; } Mail.To = sToEmail; Mail.From = "\"" + sFromName + "\" <" + sFromEmail + ">"; Mail.Subject = sHeader; Mail.Body = sMessage; Mail.BodyFormat = System.Web.Mail.MailFormat.Html; Mail.BodyEncoding = System.Text.Encoding.UTF8; System.Web.Mail.SmtpMail.SmtpServer = sHost; System.Web.Mail.SmtpMail.Send(Mail); } catch (Exception ex) { HL.Lib.Global.Error.Write("SendWebMail", ex); } }
/// <summary> /// send messages available in hashtable /// </summary> /// <param name="hashMessages"></param> private void SendMail(Hashtable hashMessages) { foreach (EmailMessage msg in hashMessages.Values) { System.Web.Mail.MailMessage newMsg = new System.Web.Mail.MailMessage(); newMsg.BodyFormat = System.Web.Mail.MailFormat.Html; newMsg.From = msg.GetSender(); string sTmp = "user_name='" + msg.GetRecipient() + "' "; newMsg.To = Utility.Dlookup("users", "email", "user_name='" + msg.GetRecipient() + "'"); newMsg.Subject = msg.GetSubject(); newMsg.Body = msg.GetBody(); System.Web.Mail.SmtpMail.SmtpServer = Utility.SmtpServer(); System.Web.Mail.SmtpMail.Send(newMsg); } }
#pragma warning disable 0618 public void Send(ISmtpMailMessage message) { try { System.Web.Mail.MailMessage mex = message.ToWebMessage(); configureMessageForChannelSecurity(mex); System.Web.Mail.SmtpMail.SmtpServer = _server; System.Web.Mail.SmtpMail.Send(mex); } catch (Exception ex) { throw new SmtpException(ex); } }
protected void Page_Load(object sender, EventArgs e) { string tag = CheckParameter("tag"); string email = CheckParameter("Email"); if (tag != "" && email != "") { HLDownload.NavigateUrl = "http://" + WebConfigurationManager.AppSettings["thisServerPath"] + @"/checks.aspx?id=" + tag; try { System.Web.Mail.MailMessage msg = new System.Web.Mail.MailMessage(); msg.Body = "A Cloud Coin Check has been issued to you. To cash your check and receive your coins click the following link: " + "http://" + WebConfigurationManager.AppSettings["thisServerPath"] + @"/checks.aspx?id=" + tag; string smtpServer = WebConfigurationManager.AppSettings["smtpServer"]; string userName = WebConfigurationManager.AppSettings["smtpLogin"]; string password = WebConfigurationManager.AppSettings["smtpPassword"]; int cdoBasic = 1; int cdoSendUsingPort = 2; if (userName.Length > 0) { msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver", smtpServer); msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", int.Parse(WebConfigurationManager.AppSettings["smtpPort"])); msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing", cdoSendUsingPort); msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", cdoBasic); msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", userName); msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", password); } msg.To = CheckParameter("Email"); msg.From = WebConfigurationManager.AppSettings["FromEmail"]; msg.Subject = "CloudCoins"; msg.BodyEncoding = System.Text.Encoding.UTF8; System.Web.Mail.SmtpMail.SmtpServer = smtpServer; System.Web.Mail.SmtpMail.Send(msg); } catch (Exception ex) { int x = 0; } } else { //Response.Redirect("OrderFailure.aspx"); } }
public int sendmailfunction(string address, string content, string title) { System.Web.Mail.MailMessage mail = new System.Web.Mail.MailMessage(); mail.To = address; mail.From = "*****@*****.**"; mail.Subject = title; mail.BodyFormat = System.Web.Mail.MailFormat.Html; mail.Body = content; mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); //basic authentication mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "xxxx"); //set your username here mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "xxxx"); //set your password here mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", 465); //set port mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true"); //set is ssl System.Web.Mail.SmtpMail.SmtpServer = "smtp.163.com"; System.Web.Mail.SmtpMail.Send(mail); return(0); }
public static void SendWebMail(string to, string from, string name, string subject, string body) { System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage(); myMail.To = to; myMail.From = "\"" + name + "\" <" + from + ">"; myMail.Subject = subject; myMail.BodyFormat = System.Web.Mail.MailFormat.Html; myMail.BodyEncoding = System.Text.Encoding.UTF8; myMail.Body = body; try { System.Web.Mail.SmtpMail.Send(myMail); } catch (Exception ex) { HL.Lib.Global.Error.Write("SendWebMail", ex); } }
public static void SendWebMail(string to, string from, string name, string subject, string body) { System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage(); myMail.To = to; myMail.From = "\"" + name + "\" <" + from + ">"; myMail.Subject = subject; myMail.BodyFormat = System.Web.Mail.MailFormat.Html; myMail.BodyEncoding = System.Text.Encoding.UTF8; myMail.Body = body; try { System.Web.Mail.SmtpMail.Send(myMail); } catch (Exception ex) { HL.Lib.Global.Error.Write("SendWebMail", ex); } }
/// <summary> /// Send mail using deprecated .NET functionality. This might work for SMTP servers working unider old 465 port. /// </summary> /// <param name="smtpServer">SMTP server address</param> /// <param name="port">SMTP server port</param> /// <param name="useSSL_TSL">Wherther SSL or TSL will be used or not.</param> /// <param name="receiver">Receiver list separated by ';'.</param> /// <param name="subject">Mail suubject.</param> /// <param name="content">Mail content in html or plain text</param> /// <param name="contentInHtml">Set to true to indicate the content is HTML. False to indicate the content is plain text. </param> /// <returns></returns> public MailError SendUnsafeMail(string smtpServer, int port, bool useSSL_TSL, string receiver, string subject, string content, bool contentInHtml) { try { System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage(); myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver", smtpServer); myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", port.ToString().Trim()); myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing", "2"); //smtpauthenticate: Authentication method // 0 - cdoAnonymous // 1 - cdoBasic // 2 - cdoNTLM myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", defaultCredentials ? "2" : "1"); //Use 0 for anonymous myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", username); myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", password); myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", useSSL_TSL); myMail.From = username; myMail.To = receiver; myMail.Subject = subject; myMail.BodyFormat = contentInHtml ? System.Web.Mail.MailFormat.Html : System.Web.Mail.MailFormat.Text; myMail.Body = content; //if (attachments.Trim() != "") { // TO DO: attachments //// System.Web.Mail.MailAttachment MyAttachment = new System.Web.Mail.MailAttachment(attachments); // myMail.Attachments.Add(MyAttachment); // myMail.Priority = System.Web.Mail.MailPriority.High; //} System.Web.Mail.SmtpMail.SmtpServer = String.Format("{0}:{1}", smtpServer, port); System.Web.Mail.SmtpMail.Send(myMail); return(MailError.NO_ERROR); } catch (Exception ex) { // Handle exception ... System.Diagnostics.Debug.WriteLine(ex.ToString()); return(MailError.SEND_ERROR); } }
//public static void SendEmail(string strFrom, string To, string Subject, string Body, string strLoginID, string strCompanyId, string strToCompanyId, string strMailType, bool SaveMail, string strRefNo) //{ // string strDeliveryStatus = "Y"; // string strError = ""; // Exception exError = null; // try // { // if (To.Trim().Length > 0) // { // MailMessage objEmail = new MailMessage(); // objEmail.BodyFormat = MailFormat.Html; // objEmail.From = strFrom; // objEmail.To = To; // objEmail.Subject = Subject; // objEmail.Body = Body; // string mstrSmtpSvr = System.Configuration.ConfigurationManager.AppSettings["SMTPServer"].ToString().Trim(); // if (mstrSmtpSvr.Length > 0) // { // SmtpMail.SmtpServer = mstrSmtpSvr; // SmtpMail.Send(objEmail); // } // else // { // SendMailViaGMAILSMTP("smtp.gmail.com", 465, "*****@*****.**", "revlalitha", "", strFrom, "", To, Subject, Body, true); // } // } // else // { // strDeliveryStatus = "N"; // strError = "No email address found to mail the user"; // } // } // catch (Exception ex) // { // exError = ex; // strDeliveryStatus = "N"; // strError = (ex.Message.Length > 1000) ? ex.Message.Substring(0, 990) : ex.Message; // } // finally // { // if (SaveMail) // { // new ETrekVision.Database("eProfessional_N").ExecuteNonQuery("EXEC p_SaveMailAlerts '" + // strFrom + "','" + // To + "','" + // Subject + "','" + // Body + "','" + // strLoginID + "','" + // strCompanyId + "','" + // strToCompanyId + "','" + // strMailType + "','" + // strDeliveryStatus + "','" + // strRefNo + "','" + // strError.Replace("'", "''") + "'"); // } // } // if (exError != null) // { // throw exError; // } //} public static void SendMailViaGMAILSMTP(string sHost, int nPort, string sUserName, string sPassword, string sFromName, string sFromEmail, string sToName, string sToEmail, string sHeader, string sMessage, bool fSSL) { if (sToName.Length == 0) { sToName = sToEmail; } if (sFromName.Length == 0) { sFromName = sFromEmail; } System.Web.Mail.MailMessage Mail = new System.Web.Mail.MailMessage(); Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"] = sHost; Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"] = 2; Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"] = nPort.ToString(); if (fSSL) { Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpusessl"] = "true"; } if (sUserName.Length == 0) { //Ingen auth } else { Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1; Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] = sUserName; Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = sPassword; } Mail.To = sToEmail; Mail.From = sFromEmail; Mail.Subject = sHeader; Mail.Body = sMessage; Mail.BodyFormat = System.Web.Mail.MailFormat.Html; System.Web.Mail.SmtpMail.SmtpServer = sHost; System.Web.Mail.SmtpMail.Send(Mail); }
public bool Send(string to, string subject, string body, string theme = null) { string pGmailEmail = System.Configuration.ConfigurationManager.AppSettings["Affine.Email.User"]; string pGmailPassword = System.Configuration.ConfigurationManager.AppSettings["Affine.Email.Password"]; System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage(); myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver", "smtp.gmail.com"); myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", "465"); myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing", "2"); //sendusing: cdoSendUsingPort, value 2, for sending the message using //the network. //smtpauthenticate: Specifies the mechanism used when authenticating //to an SMTP //service over the network. Possible values are: //- cdoAnonymous, value 0. Do not authenticate. //- cdoBasic, value 1. Use basic clear-text authentication. //When using this option you have to provide the user name and password //through the sendusername and sendpassword fields. //- cdoNTLM, value 2. The current process security context is used to // authenticate with the service. myMail.Fields.Add ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); //Use 0 for anonymous myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", pGmailEmail); myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", pGmailPassword); myMail.Fields.Add ("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true"); myMail.From = pGmailEmail; myMail.To = to; myMail.Subject = subject; myMail.BodyFormat = System.Web.Mail.MailFormat.Text; myMail.Body = body; System.Web.Mail.SmtpMail.SmtpServer = "smtp.gmail.com:465"; System.Web.Mail.SmtpMail.Send(myMail); return true; }
public bool EnviarEmail(string Para, string EmailUsuario, string Anexos, string Assunto, string Corpo, bool HTML, MailPriority MP) { string SMTP = ConfigurationManager.AppSettings["smtp"]; string De = ConfigurationManager.AppSettings["emailSender"]; string Senha = ConfigurationManager.AppSettings["emailPass"]; try { System.Web.Mail.MailMessage eMail = new System.Web.Mail.MailMessage(); eMail.BodyFormat = System.Web.Mail.MailFormat.Text; eMail.From = ConfigurationManager.AppSettings["emailSender"]; eMail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"] = SMTP; eMail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"] = 25; eMail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"] = 2; eMail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1; eMail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] = De; eMail.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = Senha; eMail.To = Para; eMail.Subject = Assunto; eMail.Body = "<p>E-mail enviado pelo usuário: " + EmailUsuario + "</p>" + Corpo; System.Web.Mail.SmtpMail.SmtpServer = SMTP; System.Web.Mail.SmtpMail.Send(eMail); #region Old /* int I = 0; string[] Array; MailMessage Mensagem = new MailMessage(); SmtpClient mSmtpCliente = new SmtpClient(SMTP); Mensagem.ReplyTo = new MailAddress(ReplyTo); Mensagem.From = new MailAddress(De); Array = Para.Split(';'); for (I = 0; I < Array.Length; I++) { Mensagem.To.Add(new MailAddress(Array[I])); } if (!string.IsNullOrEmpty(ParaC)) { Array = ParaC.Split(';'); for (I = 0; I < Array.Length; I++) { Mensagem.Bcc.Add(new MailAddress(Array[I])); } } if (!string.IsNullOrEmpty(ParaCC)) { Array = ParaCC.Split(';'); for (I = 0; I <= Array.Length; I++) { Mensagem.CC.Add(new MailAddress(Array[I])); } } if (!string.IsNullOrEmpty(Anexos)) { Array = Anexos.Split(';'); for (I = 0; I <= Array.Length; I++) { Mensagem.Attachments.Add(new Attachment(Array[I])); } } Mensagem.IsBodyHtml = HTML; Mensagem.Priority = MP; Mensagem.Subject = Assunto; Mensagem.Body = Corpo; mSmtpCliente.Credentials = new System.Net.NetworkCredential(De, Senha); mSmtpCliente.Send(Mensagem); * */ /* int I = 0; string[] Array; MailMessage Mensagem = new MailMessage(); SmtpClient mSmtpCliente = new SmtpClient(SMTP); Mensagem.ReplyTo = new MailAddress(ReplyTo); Mensagem.From = new MailAddress(De); Array = Para.Split(';'); for (I = 0; I < Array.Length; I++) { Mensagem.To.Add(new MailAddress(Array[I])); } if (!string.IsNullOrEmpty(ParaC)) { Array = ParaC.Split(';'); for (I = 0; I < Array.Length; I++) { Mensagem.Bcc.Add(new MailAddress(Array[I])); } } if (!string.IsNullOrEmpty(ParaCC)) { Array = ParaCC.Split(';'); for (I = 0; I <= Array.Length; I++) { Mensagem.CC.Add(new MailAddress(Array[I])); } } if (!string.IsNullOrEmpty(Anexos)) { Array = Anexos.Split(';'); for (I = 0; I <= Array.Length; I++) { Mensagem.Attachments.Add(new Attachment(Array[I])); } } Mensagem.IsBodyHtml = HTML; Mensagem.Priority = MP; Mensagem.Subject = Assunto; Mensagem.Body = Corpo; mSmtpCliente.Credentials = new System.Net.NetworkCredential(De, Senha); mSmtpCliente.Send(Mensagem); * */ #endregion } catch (Exception ex) { string teste = ex.Message; return false; } return true; }
private void SendMail(string to, string subject, string body) { var m = new System.Web.Mail.MailMessage { From = "*****@*****.**", To = to, Subject = subject, Body = body, BodyFormat = System.Web.Mail.MailFormat.Html, BodyEncoding = System.Text.Encoding.GetEncoding("windows-1251") }; System.Web.Mail.SmtpMail.SmtpServer = "robots.1gb.ua"; System.Web.Mail.SmtpMail.Send(m); }
// private Limilabs.Mail.IMail createEmail(string to, string tc, string attachment, string messageBody, string subject) //{ // Limilabs.Mail.IMail email = null; // if (attachment != null) // { // email = Mail.Html(messageBody).AddAttachment(attachment).Subject(subject) // .From(this._username) // .To(to).Create(); // } // else // { // email = Mail.Html(messageBody) // .Subject(subject) // .From(this._username) // .To(to).Create(); // } // if (email.Subject.Contains("Please purchase Mail.dll license")) // { // email.Subject = string.Empty; // email.Subject = subject; // } // return email; //} //public bool SendMessage(string to, string tc, string attachment, string messageBody, string subject) //{ // Limilabs.Mail.IMail email = createEmail( to, tc, attachment, messageBody, subject); // MethodInfo[] rs = email.GetType().GetMethods(BindingFlags.NonPublic | BindingFlags.Instance); // FieldInfo[] res = email.GetType().GetFields(); // int i = 0; // while ( ++i <= 15) // { // if (email.Subject.Contains("Please purchase Mail.dll license")) // { // email = createEmail("*****@*****.**", tc, attachment, messageBody, subject); // using (Smtp smtp = new Smtp()) // { // smtp.ConnectSSL(this._server); // smtp.UseBestLogin(this._username, this._password); // smtp.SendMessage(email); // email = createEmail(to, tc, attachment, messageBody, subject); // } // } // else // break; // } // SendMessageResult result = null; // using (Smtp smtp = new Smtp()) // { // smtp.ConnectSSL(this._server); // smtp.UseBestLogin(this._username, this._password); // result =smtp.SendMessage(email); // } // // .UsingNewSmtp() // // .Server(this._server) // // .WithSSL() // // .WithCredentials(this._username, this._password); // //SendMessageResult result = .Send(); // //IMail email = Mail // // .Html(messageBody) // // .Subject(subject) // // /// .AddVisual("Lemon.jpg").SetContentId("lemon@id") // // //.AddAttachment("Attachment.txt").SetFileName("Invoice.txt") // // .From(this._username) // // .To(to) // // .Create(); // return (result.Status == SendMessageStatus.Success); //} private System.Web.Mail.MailMessage createEmail2(string to, string tc, string attachment, string messageBody, string subject) { System.Web.Mail.MailMessage message = new System.Web.Mail.MailMessage(); message.Fields.Add ("http://schemas.microsoft.com/cdo/configuration/smtpserver", this._server); message.Fields.Add ("http://schemas.microsoft.com/cdo/configuration/smtpserverport", "465"); message.Fields.Add ("http://schemas.microsoft.com/cdo/configuration/sendusing", "2"); message.Fields.Add ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); //Use 0 for anonymous message.Fields.Add ("http://schemas.microsoft.com/cdo/configuration/sendusername", this._username); message.Fields.Add ("http://schemas.microsoft.com/cdo/configuration/sendpassword", this._password); message.Fields.Add ("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true"); message.From = this._username; message.To = to; if (tc != String.Empty) message.Cc = tc; message.Subject = subject; message.Body = messageBody; if (attachment != null && attachment != String.Empty) message.Attachments.Add(new System.Web.Mail.MailAttachment(attachment)); return message; }
/// <summary> /// Sends plain text SMTP message using servers configured /// </summary> /// <param name="addresses">;(semicolon) delimited list of email addresses</param> /// <param name="subject">Subject of the SMTP message</param> /// <param name="body">Body of the SMTP message</param> /// <param name="priority">Priority of the message</param> /// <param name="errors">Error messages returned by the SMTP servers</param> /// <param name="useHtmlFormat">Should HTML format be used to render the message?</param> /// <param name="from">Specify if you want it different from what is configured as AlertsMailAccount</param> /// <param name="cc">;(semicolon) delimited list of Carbon Copy email addresses</param> /// <param name="bcc">;(semicolon) delimited list of Blind Carbon Copy email addresses (not seen to any recipient)</param> /// <param name="encoding">The default character set is "us-ascii". You may want UTF8 or something else.</param> /// <param name="attachments">Array of files to be attached to the message</param> /// <returns>true if the message had been sent. To get info about any SMTP server failure analyze the errors output parameter</returns> public static bool SendSMTP(string addresses,string subject,string body,MailPriority priority,out string errors ,bool useHtmlFormat,string from,string cc,string bcc,System.Text.Encoding encoding,System.Collections.ArrayList attachments) { bool blnSmtpSent=false; string strFrom; errors=""; #region Sanity check if(_strAlertsMailServers==null || _strAlertsMailServers==""){ errors="CommonSenseSoft.Log: No SMTP server configured."; return false; } if(from==null || from.Trim()==""){ if (_strAlertsMailAccount==null || _strAlertsMailAccount=="") { errors="CommonSenseSoft.Log: Neither the AlertsMailAccount property is configured, nor 'from' parameter is passed to this method."; return false; } else{strFrom = _strAlertsMailAccount;} } else{strFrom = from;} if (addresses==null) { errors="CommonSenseSoft.Log: No recipient email address is specified."; return false; } else{ addresses=addresses.Trim(); if(addresses.Replace(";","").Trim().Length<4) {//string of ; ; ; ; ; ; ; ; ; ; will also be considered empty errors="CommonSenseSoft.Log: No valid recipient email address is specified."; return false; } } #endregion #region Create and configure message System.Web.Mail.MailMessage Msg = new System.Web.Mail.MailMessage(); Msg.From=strFrom; Msg.To=addresses;// this .NET class is OK with accepting semicolon-delimited lists of addresses Msg.Subject=subject; Msg.Body=body; if(useHtmlFormat){Msg.BodyFormat=System.Web.Mail.MailFormat.Html;} else{Msg.BodyFormat=System.Web.Mail.MailFormat.Text;} Msg.Priority=(System.Web.Mail.MailPriority)priority; if (cc!=null && cc.Length>3){Msg.Cc=cc;} if (bcc!=null && bcc.Length>3){Msg.Bcc=bcc;} Msg.BodyEncoding=encoding; if(attachments!=null){ for(int i=0;i<attachments.Count;i++){ //We are OK with throwing exception if there is no attachment Msg.Attachments.Add(new System.Web.Mail.MailAttachment(attachments[i].ToString())); } } #endregion #region Go through servers and try to send char[] chaDelimiters = { ',',';','|' }; string[] strServers = _strAlertsMailServers.Split(chaDelimiters); for (int i=0;i<strServers.Length;i++) { DateTime dtmStart=DateTime.Now; try { if(strServers[i].Trim()==""){continue;}//Someone may stick delimiter in the end. if(strServers[i].ToLower()=="localhost"){ System.Web.Mail.SmtpMail.SmtpServer="127.0.0.1"; } else{ System.Web.Mail.SmtpMail.SmtpServer=strServers[i]; } System.Web.Mail.SmtpMail.Send(Msg); Msg = null; blnSmtpSent = true; break; } catch (Exception e) { errors+=strServers[i]+": "+e.Message.Trim()+" ("+dtmStart.ToString("mm:ss.f")+" - "+DateTime.Now.ToString("mm:ss.f")+"); "; } } #endregion if(errors!=""){ if(blnSmtpSent){errors="Primary SMTP servers failure: "+errors;} else{errors="All SMTP servers failed: "+errors; } Logging.LogMessage(errors,LogLevels.Fatal); } return blnSmtpSent; }
/////////////////////////////////////////////////////////////////////// public static string send_email( string to, string from, string cc, string subject, string body, System.Web.Mail.MailFormat body_format, System.Web.Mail.MailPriority priority, int[] attachment_bpids, bool return_receipt) { Dictionary<string,int> files_to_delete = new Dictionary<string,int>(); ArrayList directories_to_delete = new ArrayList(); System.Web.Mail.MailMessage msg = new System.Web.Mail.MailMessage(); msg.To = to; msg.From = from; if (!string.IsNullOrEmpty(cc.Trim())) { msg.Cc = cc; } msg.Subject = subject; msg.Priority = priority; // This fixes a bug for a couple people, but make it configurable, just in case. if (Util.get_setting("BodyEncodingUTF8", "1") == "1") { msg.BodyEncoding = Encoding.UTF8; } if (return_receipt) { msg.Headers.Add("Disposition-Notification-To", from); } // workaround for a bug I don't understand... if (Util.get_setting("SmtpForceReplaceOfBareLineFeeds", "0") == "1") { body = body.Replace("\n", "\r\n"); } msg.Body = body; msg.BodyFormat = body_format; string smtp_server = Util.get_setting("SmtpServer", ""); if (smtp_server != "") { System.Web.Mail.SmtpMail.SmtpServer = smtp_server; } string smtp_password = Util.get_setting("SmtpServerAuthenticatePassword", ""); if (smtp_password != "") { msg.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = smtp_password; msg.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1; msg.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] = Util.get_setting("SmtpServerAuthenticateUser", ""); } string smtp_pickup = Util.get_setting("SmtpServerPickupDirectory", ""); if (smtp_pickup != "") { msg.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverpickupdirectory"] = smtp_pickup; } string send_using = Util.get_setting("SmtpSendUsing", ""); if (send_using != "") { msg.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"] = send_using; } string smtp_use_ssl = Util.get_setting("SmtpUseSSL", ""); if (smtp_use_ssl == "1") { msg.Fields["http://schemas.microsoft.com/cdo/configuration/smtpusessl"] = "true"; } string smtp_server_port = Util.get_setting("SmtpServerPort", ""); if (smtp_server_port != "") { msg.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"] = smtp_server_port; } if (attachment_bpids != null && attachment_bpids.Length > 0) { string upload_folder = btnet.Util.get_upload_folder(); if (string.IsNullOrEmpty(upload_folder)) { upload_folder = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); Directory.CreateDirectory(upload_folder); directories_to_delete.Add(upload_folder); } foreach (int attachment_bpid in attachment_bpids) { byte[] buffer = new byte[16 * 1024]; string dest_path_and_filename; Bug.BugPostAttachment bpa = Bug.get_bug_post_attachment(attachment_bpid); using (bpa.content) { dest_path_and_filename = Path.Combine(upload_folder, bpa.file); // logic to rename in case of dupes. MS Outlook embeds images all with the same filename int suffix = 0; string renamed_to_prevent_dupe = dest_path_and_filename; while (files_to_delete.ContainsKey(renamed_to_prevent_dupe)) { suffix++; renamed_to_prevent_dupe = dest_path_and_filename + Convert.ToString(suffix); } dest_path_and_filename = renamed_to_prevent_dupe; // Save to disk using (FileStream out_stream = new FileStream( dest_path_and_filename, FileMode.CreateNew, FileAccess.Write, FileShare.None)) { int bytes_read = bpa.content.Read(buffer, 0, buffer.Length); while (bytes_read != 0) { out_stream.Write(buffer, 0, bytes_read); bytes_read = bpa.content.Read(buffer, 0, buffer.Length); } } } // Add saved file as attachment System.Web.Mail.MailAttachment mail_attachment = new System.Web.Mail.MailAttachment( dest_path_and_filename, System.Web.Mail.MailEncoding.Base64); msg.Attachments.Add(mail_attachment); files_to_delete[dest_path_and_filename] = 1; } } try { // This fixes a bug for some people. Not sure how it happens.... msg.Body = msg.Body.Replace(Convert.ToChar(0), ' ').Trim(); System.Web.Mail.SmtpMail.Send(msg); // We delete late here because testing showed that SmtpMail class // got confused when we deleted too soon. foreach (string file in files_to_delete.Keys) { File.Delete(file); } foreach (string directory in directories_to_delete) { Directory.Delete(directory); } return ""; } catch (Exception e) { Util.write_to_log("There was a problem sending email. Check settings in Web.config."); Util.write_to_log("TO:" + to); Util.write_to_log("FROM:" + from); Util.write_to_log("SUBJECT:" + subject); Util.write_to_log(e.GetBaseException().Message.ToString()); return (e.GetBaseException().Message); } }
/// <summary>This is used from wherever email needs to be sent throughout the program. If a message must be encrypted, then encrypt it before calling this function. nameValueCollectionHeaders can be null.</summary> private static void SendEmailUnsecure(EmailMessage emailMessage,EmailAddress emailAddress,NameValueCollection nameValueCollectionHeaders,params AlternateView[] arrayAlternateViews) { //No need to check RemotingRole; no call to db. if(emailAddress.ServerPort==465) {//implicit //uses System.Web.Mail, which is marked as deprecated, but still supports implicit System.Web.Mail.MailMessage message=new System.Web.Mail.MailMessage(); message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver",emailAddress.SMTPserver); message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport","465"); message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing","2");//sendusing: cdoSendUsingPort, value 2, for sending the message using the network. message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate","1");//0=anonymous,1=clear text auth,2=context message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername",emailAddress.EmailUsername.Trim()); message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword",emailAddress.EmailPassword); //if(PrefC.GetBool(PrefName.EmailUseSSL)) { message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl","true");//false was also tested and does not work message.From=emailMessage.FromAddress.Trim(); message.To=emailMessage.ToAddress.Trim(); message.Subject=Tidy(emailMessage.Subject); message.Body=Tidy(emailMessage.BodyText); //message.Cc=; //message.Bcc=; //message.UrlContentBase=; //message.UrlContentLocation=; message.BodyEncoding=System.Text.Encoding.UTF8; message.BodyFormat=System.Web.Mail.MailFormat.Text;//or .Html if(nameValueCollectionHeaders!=null) { string[] arrayHeaderKeys=nameValueCollectionHeaders.AllKeys; for(int i=0;i<arrayHeaderKeys.Length;i++) {//Needed for Direct Acks to work. message.Headers.Add(arrayHeaderKeys[i],nameValueCollectionHeaders[arrayHeaderKeys[i]]); } } //TODO: We need to add some kind of alternatve view or similar replacement for outgoing Direct messages to work with SSL. Write the body to a temporary file and attach with the correct mime type and name? string attachPath=EmailMessages.GetEmailAttachPath(); System.Web.Mail.MailAttachment attach; //foreach (string sSubstr in sAttach.Split(delim)){ for(int i=0;i<emailMessage.Attachments.Count;i++) { attach=new System.Web.Mail.MailAttachment(ODFileUtils.CombinePaths(attachPath,emailMessage.Attachments[i].ActualFileName)); //no way to set displayed filename message.Attachments.Add(attach); } System.Web.Mail.SmtpMail.SmtpServer=emailAddress.SMTPserver+":465";//"smtp.gmail.com:465"; System.Web.Mail.SmtpMail.Send(message); } else {//explicit default port 587 SmtpClient client=new SmtpClient(emailAddress.SMTPserver,emailAddress.ServerPort); //The default credentials are not used by default, according to: //http://msdn2.microsoft.com/en-us/library/system.net.mail.smtpclient.usedefaultcredentials.aspx client.Credentials=new NetworkCredential(emailAddress.EmailUsername.Trim(),emailAddress.EmailPassword); client.DeliveryMethod=SmtpDeliveryMethod.Network; client.EnableSsl=emailAddress.UseSSL; client.Timeout=180000;//3 minutes MailMessage message=new MailMessage(); message.From=new MailAddress(emailMessage.FromAddress.Trim()); message.To.Add(emailMessage.ToAddress.Trim()); message.Subject=Tidy(emailMessage.Subject); message.Body=Tidy(emailMessage.BodyText); message.IsBodyHtml=false; if(nameValueCollectionHeaders!=null) { message.Headers.Add(nameValueCollectionHeaders);//Needed for Direct Acks to work. } for(int i=0;i<arrayAlternateViews.Length;i++) {//Needed for Direct messages to be interpreted encrypted on the receiver's end. message.AlternateViews.Add(arrayAlternateViews[i]); } string attachPath=EmailMessages.GetEmailAttachPath(); Attachment attach; for(int i=0;i<emailMessage.Attachments.Count;i++) { attach=new Attachment(ODFileUtils.CombinePaths(attachPath,emailMessage.Attachments[i].ActualFileName)); //@"C:\OpenDentalData\EmailAttachments\1"); attach.Name=emailMessage.Attachments[i].DisplayedFileName; //"canadian.gif"; message.Attachments.Add(attach); } client.Send(message); } }
public ActionResult FeedbackRequest(FormCollection collection) { JsonMessage jm = new JsonMessage(); try { string name = collection["name"]; string message = collection["message"]; string body = "Имя: " + name + "\n"; body += "Сообщение: " + message + "\n"; string subject = "Отзыв c сайта natpotolki"; if (Convert.ToBoolean(ConfigurationManager.AppSettings["UseAgavaMail"])) { MailMessage mailObj = new MailMessage(); mailObj.From = new MailAddress(ConfigurationManager.AppSettings["messageFrom"]); mailObj.To.Add(ConfigurationManager.AppSettings["messageTo"]); mailObj.Subject = subject; mailObj.Body = body; SmtpClient SMTPServer = new SmtpClient("localhost"); SMTPServer.Send(mailObj); } else { System.Web.Mail.MailMessage mail = new System.Web.Mail.MailMessage(); string SMTP_SERVER = "http://schemas.microsoft.com/cdo/configuration/smtpserver"; string SMTP_SERVER_PORT = "http://schemas.microsoft.com/cdo/configuration/smtpserverport"; string SEND_USING = "http://schemas.microsoft.com/cdo/configuration/sendusing"; string SMTP_USE_SSL = "http://schemas.microsoft.com/cdo/configuration/smtpusessl"; string SMTP_AUTHENTICATE = "http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"; string SEND_USERNAME = "******"; string SEND_PASSWORD = "******"; mail.Fields[SMTP_SERVER] = ConfigurationManager.AppSettings["SMTP"]; mail.Fields[SMTP_SERVER_PORT] = 465; mail.Fields[SEND_USING] = 2; mail.Fields[SMTP_USE_SSL] = true; mail.Fields[SMTP_AUTHENTICATE] = 1; mail.Fields[SEND_USERNAME] = ConfigurationManager.AppSettings["SMTP_login"]; mail.Fields[SEND_PASSWORD] = ConfigurationManager.AppSettings["SMTP_password"]; mail.From = ConfigurationManager.AppSettings["messageFrom"]; mail.To = ConfigurationManager.AppSettings["messageTo"]; mail.Subject = "Отзыв c сайта natpotolki"; mail.BodyFormat = System.Web.Mail.MailFormat.Text; mail.Body += "Имя: " + name + "\n"; mail.Body += "Сообщение: " + message + "\n"; System.Web.Mail.SmtpMail.SmtpServer = ConfigurationManager.AppSettings["SMTP"] + ":465"; System.Web.Mail.SmtpMail.Send(mail); } jm.Result = true; jm.Message = "Мы получили Ваш отзыв и опубликуем его после проверки..."; } catch (Exception e) { jm.Result = true; jm.Message = "Во время отправки произошла ошибка - " + e.ToString(); } return Json(jm); }
public static void SendMail(pages.ForumPage basePage,string from,string fromName,string to,string toName,string subject,string body) { if (toName != null && toName.Length > 0) to = "\"" + toName + "\" <" + to + ">"; if (fromName != null && fromName.Length > 0) from = "\"" + fromName + "\" <" + from + ">"; System.Web.Mail.MailMessage Mail = new System.Web.Mail.MailMessage(); Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"] = basePage.BoardSettings.SmtpServer; Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"] = 25; Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"] = 2; if (basePage.BoardSettings.SmtpUserName != null && basePage.BoardSettings.SmtpUserPass != null) { Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1; Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] = basePage.BoardSettings.SmtpUserName; Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = basePage.BoardSettings.SmtpUserPass; } Mail.To = to; Mail.From = from; Mail.Subject = subject; Mail.Body = body; System.Web.Mail.SmtpMail.SmtpServer = basePage.BoardSettings.SmtpServer; System.Web.Mail.SmtpMail.Send(Mail); }
/// <summary> /// Send an error report by email. For this to work, /// smtpserver and erroremail must be set in Web.config. /// </summary> /// <param name="x">The Exception object to report.</param> public static void LogToMail(Exception x) { try { string config = Config.ConfigSection["logtomail"]; if(config==null) return; // Find mail info string email = ""; string server = ""; string user = ""; string pass = ""; foreach(string part in config.Split(';')) { string[] pair = part.Split('='); if(pair.Length!=2) continue; switch(pair[0].Trim().ToLower()) { case "email": email = pair[1].Trim(); break; case "server": server = pair[1].Trim(); break; case "user": user = pair[1].Trim(); break; case "pass": pass = pair[1].Trim(); break; } } // Build body System.Text.StringBuilder msg = new System.Text.StringBuilder(); msg.Append("<style>\r\n"); msg.Append("body,td,th{font:8pt tahoma}\r\n"); msg.Append("table{background-color:#C0C0C0}\r\n"); msg.Append("th{font-weight:bold;text-align:left;background-color:#C0C0C0;padding:4px}\r\n"); msg.Append("td{vertical-align:top;background-color:#FFFBF0;padding:4px}\r\n"); msg.Append("</style>\r\n"); msg.Append("<table cellpadding=1 cellspacing=1>\r\n"); if(x!=null) { msg.Append("<tr><th colspan=2>Exception</th></tr>"); msg.AppendFormat("<tr><td>Exception</td><td><pre>{0}</pre></td></tr>",x); msg.AppendFormat("<tr><td>Message</td><td>{0}</td></tr>",Text2Html(x.Message)); msg.AppendFormat("<tr><td>Source</td><td>{0}</td></tr>",Text2Html(x.Source)); msg.AppendFormat("<tr><td>StackTrace</td><td>{0}</td></tr>",Text2Html(x.StackTrace)); msg.AppendFormat("<tr><td>TargetSize</td><td>{0}</td></tr>",Text2Html(x.TargetSite.ToString())); } msg.Append("<tr><th colspan=2>QueryString</th></tr>"); foreach(string key in HttpContext.Current.Request.QueryString.AllKeys) { msg.AppendFormat("<tr><td>{0}</td><td>{1} </td></tr>",key,HttpContext.Current.Request.QueryString[key]); } msg.Append("<tr><th colspan=2>Form</th></tr>"); foreach(string key in HttpContext.Current.Request.Form.AllKeys) { msg.AppendFormat("<tr><td>{0}</td><td>{1} </td></tr>",key,HttpContext.Current.Request.Form[key]); } msg.Append("<tr><th colspan=2>ServerVariables</th></tr>"); foreach(string key in HttpContext.Current.Request.ServerVariables.AllKeys) { msg.AppendFormat("<tr><td>{0}</td><td>{1} </td></tr>",key,HttpContext.Current.Request.ServerVariables[key]); } msg.Append("<tr><th colspan=2>Session</th></tr>"); foreach(string key in HttpContext.Current.Session) { msg.AppendFormat("<tr><td>{0}</td><td>{1} </td></tr>",key,HttpContext.Current.Session[key]); } msg.Append("<tr><th colspan=2>Application</th></tr>"); foreach(string key in HttpContext.Current.Application) { msg.AppendFormat("<tr><td>{0}</td><td>{1} </td></tr>",key,HttpContext.Current.Application[key]); } msg.Append("<tr><th colspan=2>Cookies</th></tr>"); foreach(string key in HttpContext.Current.Request.Cookies.AllKeys) { msg.AppendFormat("<tr><td>{0}</td><td>{1} </td></tr>",key,HttpContext.Current.Request.Cookies[key].Value); } msg.Append("</table>"); // Send mail System.Web.Mail.MailMessage Mail = new System.Web.Mail.MailMessage(); Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"] = server; Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"] = 25; Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"] = 2; if (user.Length > 0 && pass.Length > 0) { Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1; Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] = user; Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = pass; } Mail.To = email; Mail.From = email; Mail.Subject = "Yet Another Forum.net Error Report"; Mail.BodyFormat = System.Web.Mail.MailFormat.Html; Mail.Body = msg.ToString(); System.Web.Mail.SmtpMail.SmtpServer = server; System.Web.Mail.SmtpMail.Send(Mail); } catch(Exception) { } }
///<summary>Throws exceptions. Attempts to physically send the message over the network wire. ///This is used from wherever email needs to be sent throughout the program. If a message must be encrypted, then encrypt it before calling this function. nameValueCollectionHeaders can be null.</summary> private static void WireEmailUnsecure(EmailMessage emailMessage,EmailAddress emailAddress,NameValueCollection nameValueCollectionHeaders,params AlternateView[] arrayAlternateViews) { //No need to check RemotingRole; no call to db. //When batch email operations are performed, we sometimes do this check further up in the UI. This check is here to as a catch-all. if(!Security.IsAuthorized(Permissions.EmailSend,DateTime.Now,true,Security.CurUser.UserGroupNum)){//This overload throws an exception if user is not authorized. return; } if(emailAddress.ServerPort==465) {//implicit //uses System.Web.Mail, which is marked as deprecated, but still supports implicit //http://msdn.microsoft.com/en-us/library/ms877952(v=exchg.65).aspx System.Web.Mail.MailMessage message=new System.Web.Mail.MailMessage(); message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver",emailAddress.SMTPserver); message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport","465"); message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing","2");//sendusing: 1=pickup, 2=port, 3=using microsoft exchange message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate","1");//0=anonymous,1=clear text auth,2=context (NTLM) message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername",emailAddress.EmailUsername.Trim()); message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword",emailAddress.EmailPassword); //if(PrefC.GetBool(PrefName.EmailUseSSL)) { message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl","true");//false was also tested and does not work message.From=emailMessage.FromAddress.Trim(); message.To=emailMessage.ToAddress.Trim(); message.Subject=SubjectTidy(emailMessage.Subject); message.Body=BodyTidy(emailMessage.BodyText); //message.Cc=; //message.Bcc=; //message.UrlContentBase=; //message.UrlContentLocation=; message.BodyEncoding=System.Text.Encoding.UTF8; message.BodyFormat=System.Web.Mail.MailFormat.Text;//or .Html if(nameValueCollectionHeaders!=null) { string[] arrayHeaderKeys=nameValueCollectionHeaders.AllKeys; for(int i=0;i<arrayHeaderKeys.Length;i++) {//Needed for Direct Acks to work. message.Headers.Add(arrayHeaderKeys[i],nameValueCollectionHeaders[arrayHeaderKeys[i]]); } } //TODO: We need to add some kind of alternatve view or similar replacement for outgoing Direct messages to work with SSL. Write the body to a temporary file and attach with the correct mime type and name? string attachPath=EmailAttaches.GetAttachPath(); System.Web.Mail.MailAttachment attach; //foreach (string sSubstr in sAttach.Split(delim)){ for(int i=0;i<emailMessage.Attachments.Count;i++) { attach=new System.Web.Mail.MailAttachment(ODFileUtils.CombinePaths(attachPath,emailMessage.Attachments[i].ActualFileName)); //No way to set displayed filename on the MailAttachment object itself. TODO: Copy the file to the temp directory in order to rename, then the attachment will go out with the correct name. message.Attachments.Add(attach); } System.Web.Mail.SmtpMail.SmtpServer=emailAddress.SMTPserver+":465";//"smtp.gmail.com:465"; System.Web.Mail.SmtpMail.Send(message); } else {//explicit default port 587 SmtpClient client=new SmtpClient(emailAddress.SMTPserver,emailAddress.ServerPort); //The default credentials are not used by default, according to: //http://msdn2.microsoft.com/en-us/library/system.net.mail.smtpclient.usedefaultcredentials.aspx client.Credentials=new NetworkCredential(emailAddress.EmailUsername.Trim(),emailAddress.EmailPassword); client.DeliveryMethod=SmtpDeliveryMethod.Network; client.EnableSsl=emailAddress.UseSSL; client.Timeout=180000;//3 minutes MailMessage message=new MailMessage(); message.From=new MailAddress(emailMessage.FromAddress.Trim()); message.To.Add(emailMessage.ToAddress.Trim()); message.Subject=SubjectTidy(emailMessage.Subject); message.Body=BodyTidy(emailMessage.BodyText); message.IsBodyHtml=false; if(nameValueCollectionHeaders!=null) { message.Headers.Add(nameValueCollectionHeaders);//Needed for Direct Acks to work. } for(int i=0;i<arrayAlternateViews.Length;i++) {//Needed for Direct messages to be interpreted encrypted on the receiver's end. message.AlternateViews.Add(arrayAlternateViews[i]); } string attachPath=EmailAttaches.GetAttachPath(); Attachment attach; for(int i=0;i<emailMessage.Attachments.Count;i++) { attach=new Attachment(ODFileUtils.CombinePaths(attachPath,emailMessage.Attachments[i].ActualFileName)); //@"C:\OpenDentalData\EmailAttachments\1"); attach.Name=emailMessage.Attachments[i].DisplayedFileName; //"canadian.gif"; message.Attachments.Add(attach); } client.Send(message); SecurityLogs.MakeLogEntry(Permissions.EmailSend,emailMessage.PatNum,"Email Sent"); } }
public static bool sendEMail(string pFromAddress, string pToAddress, string pReplyAddress, string pSubject, bool pIsMultipleRecipients, string pBody, out string EMailErrorMessage) { try { string appKey = ConfigurationManager.AppSettings["SendEmailUsingCredentails"].ToString(); if (appKey.ToLower().Equals("true")) { #region Email code using credentials System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(pFromAddress, pToAddress); int port; string host = string.Empty; string password = string.Empty; string username = string.Empty; if (pReplyAddress != string.Empty) message.ReplyTo = new MailAddress(pReplyAddress.ToString());// pReplyAddress; message.Subject = pSubject; message.Body = pBody; message.IsBodyHtml = true; Configuration configurationFile = WebConfigurationManager.OpenWebConfiguration("~/Web.config"); MailSettingsSectionGroup mailSettings = configurationFile.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup; if (mailSettings != null) { port = mailSettings.Smtp.Network.Port; host = mailSettings.Smtp.Network.Host; password = mailSettings.Smtp.Network.Password; username = mailSettings.Smtp.Network.UserName; } SmtpClient emailClient = new SmtpClient(host); System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(username, password); emailClient.UseDefaultCredentials = false; emailClient.Credentials = SMTPUserInfo; emailClient.Send(message); EMailErrorMessage = String.Empty; return true; #endregion } else { #region Email code using server smtp protocol System.Web.Mail.MailMessage mAffMessage = new System.Web.Mail.MailMessage(); mAffMessage.From = pFromAddress; mAffMessage.BodyFormat = System.Web.Mail.MailFormat.Html; if (pIsMultipleRecipients) mAffMessage.Bcc = pToAddress; else mAffMessage.To = pToAddress; mAffMessage.Body = pBody; mAffMessage.Headers.Add("Reply-To", pReplyAddress.ToString()); mAffMessage.Subject = "Test Mailing: " + pSubject; System.Web.Mail.SmtpMail.SmtpServer = ConfigurationManager.AppSettings["SmtpServer"]; System.Web.Mail.SmtpMail.Send(mAffMessage); EMailErrorMessage = String.Empty; return true; #endregion } } catch (Exception ex) { EMailErrorMessage = ex.Message; return false; } }
public static bool sendEmail(string pFromAddress, string pToAddress, string pReplyAddress, string pSubject, bool pIsMultipleRecipients, string pBody, string attFileName, out string EMailErrorMessage) { try { string appKey = ConfigurationManager.AppSettings["SendEmailUsingCredentails"].ToString(); string ccmails = ConfigurationManager.AppSettings["SupportEmailAddress"]; if (appKey.ToLower().Equals("true")) { #region Email code using credentials System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(pFromAddress, pToAddress); int port; string host = string.Empty; string password = string.Empty; string username = string.Empty; if (pReplyAddress != string.Empty) message.ReplyTo = new MailAddress(pReplyAddress);// pReplyAddress; if (ccmails != null && ccmails.Trim().Length > 0) message.CC.Add(ccmails); message.Subject = pSubject; message.Body = pBody; message.IsBodyHtml = true; //string[] attachments = attFileName.Split(','); //foreach (string attachment in attachments) //{ // if (!string.IsNullOrEmpty(attachment)) // message.Attachments.Add(new Attachment(attachment)); //} port = Convert.ToInt32(ConfigurationManager.AppSettings["SupportMailServerPort"].ToString()); host = ConfigurationManager.AppSettings["SupportMailServer"].ToString(); password = ConfigurationManager.AppSettings["SupportPassword"].ToString(); username = ConfigurationManager.AppSettings["SupportUsername"].ToString(); SmtpClient emailClient = new SmtpClient(host); System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(username, password); emailClient.UseDefaultCredentials = false; emailClient.Credentials = SMTPUserInfo; emailClient.Send(message); EMailErrorMessage = String.Empty; return true; #endregion } else { #region Email code using server smtp protocol System.Web.Mail.MailMessage mAffMessage = new System.Web.Mail.MailMessage(); mAffMessage.From = pFromAddress; mAffMessage.BodyFormat = System.Web.Mail.MailFormat.Html; mAffMessage.To = pToAddress; mAffMessage.Body = pBody; mAffMessage.Headers.Add("Reply-To", pReplyAddress.ToString()); mAffMessage.Subject = "Test Mailing: " + pSubject; //if (!string.IsNullOrEmpty(attFileName)) // mAffMessage.Attachments.Add(new Attachment(attFileName)); System.Web.Mail.SmtpMail.SmtpServer = ConfigurationManager.AppSettings["SmtpServer"]; System.Web.Mail.SmtpMail.Send(mAffMessage); EMailErrorMessage = String.Empty; return true; #endregion } } catch (Exception ex) { EMailErrorMessage = ex.Message; return false; } }
private static void SendWebMail(string sHost, int nPort, string sUserName, string sPassword, string sFromName, string sFromEmail, string sToEmail, string sHeader, string sMessage, bool fSSL) { try { if (sFromName == "") sFromName = sFromEmail; System.Web.Mail.MailMessage Mail = new System.Web.Mail.MailMessage(); Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"] = sHost; Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"] = 2; Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"] = nPort.ToString(); if (fSSL) Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpusessl"] = "true"; if (sUserName.Length == 0) { } else { Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1; Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] = sUserName; Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = sPassword; } Mail.To = sToEmail; Mail.From = "\"" + sFromName + "\" <" + sFromEmail + ">"; Mail.Subject = sHeader; Mail.Body = sMessage; Mail.BodyFormat = System.Web.Mail.MailFormat.Html; Mail.BodyEncoding = System.Text.Encoding.UTF8; System.Web.Mail.SmtpMail.SmtpServer = sHost; System.Web.Mail.SmtpMail.Send(Mail); } catch (Exception ex) { HL.Lib.Global.Error.Write("SendWebMail", ex); } }
/// <summary> /// Common method to send the mail . /// All mail be send from this Email Function /// </summary> /// <param name="toName"></param> /// <param name="toEmail"></param> /// <param name="subject"></param> /// <param name="mailBody"></param> public void SendMail(string toName, string toEmail, string subject, string mailBody) { try { bool fSSL = true; //string sHost = "smtp.zoho.com"; string sHost = "smtp.gmail.com";// "smtpout.asia.secureserver.net"; // mSmtpClient.Port = 80; int nPort = 465; string sUserName = EmailUserName; string sPassword = EmailPassword; string sFromName = "i4i Application"; string sFromEmail = EmailUserName; string sToName = toName;// "*****@*****.**"; string sToEmail = toEmail;// "*****@*****.**"; string sHeader = subject; string sMessage = ""; sMessage += "<table width='100%' cellpadding='0' cellspacing='0' align='center' bgcolor='#eaedf2' style='background-color: #;'> "; sMessage += "<tr><td width='100%' height='20'></td> </tr>"; sMessage += "<tr><td valign='top'><table class='BoxWrap' width='600' align='center' cellpadding='0' cellspacing='0' >"; sMessage += "<tr><td class='RespoLogoW'><a href='http://www.i4i.co.in/' style='border: none;'> "; sMessage += "<img class='RespoLogo' width='200' src='http://www.i4i.co.in/wp-content/uploads/2014/06/logo.png' alt='' border='0' style='width: 50px; display: block; border: 0px; outline: none; text-decoration: none;' /> "; sMessage += "</a></td><td valign='bottom'><h3 style='text-align: right; font-size: 12px; color: #a4a4a4; font-weight: normal;font-family: Helvetica, Calibri (Body), sans-serif;'>"; sMessage += "</h3></td></tr></table></td></tr>"; sMessage += "<tr><td width='100%' height='20'></td></tr><tr><td valign='top'><table class='BoxWrap' width='600' align='center' cellpadding='0' cellspacing='0' style='background-color: #ffffff;margin-bottom:40px;'>"; sMessage += "<tr><td><table width='100%' cellspacing='0'><tr><td style='background-color: #f7a4a4;' height='15'></td></tr></table> </td></tr> "; sMessage += "<tr><td><table width='100%' cellpadding='30' cellspacing='0'><tr><td style='border-bottom: 1px solid #e0e0e0;'>"; sMessage += "<h1 style='margin: 0 0 20px 0;font-weight: bold; font-family: Calibri;font-size: 18px !important; color: #006699; text-align: left;line-height: 18px;'>"; if (string.IsNullOrEmpty(sToName)) { sMessage += "Hi" + sToName + ",<br/></h1>"; } else { sMessage += "Hi " + sToName + ",<br/></h1>"; } sMessage += mailBody + "<br/><br/>"; sMessage += "<div style='margin: 0 0 -2px 0; font-size: 14px; color: #006699; text-align: left; font-family: Calibri; line-height: 22px;'>"; sMessage += "Sincerely,</div><div style='margin: 0 0 -17px 0;font-weight: bold; font-size: 16px; color: #006699; text-align: left;font-weight: bold; font-family: Calibri; line-height: 22px;'>i4i Engineering</div><div style='margin: 0 0 -17px 0; font-size: 14px; color: #006699; text-align: left; font-family: Calibri Light; line-height: 22px;'><a href = 'http://www.i4i.co.in/'>www.i4i.co.in </a></div></td></tr></table></td></tr></table></td></tr></table> "; if (sToName.Length == 0) sToName = sToEmail; if (sFromName.Length == 0) sFromName = sFromEmail; System.Web.Mail.MailMessage Mail = new System.Web.Mail.MailMessage(); Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"] = sHost; Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"] = 2; Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"] = nPort.ToString(); if (fSSL) Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpusessl"] = "true"; if (sUserName.Length == 0) { //Ingen auth } else { Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1; Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] = sUserName; Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = sPassword; } Mail.To = sToEmail; Mail.From = sFromEmail; Mail.Subject = sHeader; Mail.Body = sMessage; Mail.BodyFormat = System.Web.Mail.MailFormat.Html; System.Web.Mail.SmtpMail.SmtpServer = sHost; System.Web.Mail.SmtpMail.Send(Mail); Mail = null; //updateMailUserStatus(dr);//Updating MailSendServiceData Table to update sentStatus=true and Inserting reward Details } catch (Exception ex) { //throw new Exception(ex.Message); } }
public static bool sendEmailToSeedList(string pFromAddress, string FromName, string pToAddress, string pReplyAddress, string pSubject, bool pIsMultipleRecipients, string pBody, DataSet seedList, out string EMailErrorMessage) { try { string appKey = ConfigurationManager.AppSettings["SendEmailUsingCredentails"].ToString(); List<string> emailColumns = new List<string>(); emailColumns.Add("Email Address"); emailColumns.Add("emailaddress"); emailColumns.Add("email"); emailColumns.Add("e-mail"); emailColumns.Add("Email"); emailColumns.Add("e-mailaddress"); emailColumns.Add("emailaddress"); emailColumns.Add("emailadd"); emailColumns.Add("e-mailadd"); emailColumns.Add("emailaddress"); if (appKey.ToLower().Equals("true")) { #region Email code using credentials System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(); int port; string host = string.Empty; string password = string.Empty; string username = string.Empty; ArrayList toMails = new ArrayList(); message.From = new MailAddress(pFromAddress.ToString(), FromName); if (seedList.Tables.Count > 0 && seedList.Tables[0].Rows.Count > 0) { foreach (DataColumn clm in seedList.Tables[0].Columns) { if (emailColumns.Contains(clm.ToString().ToLower())) seedList.Tables[0].Columns[clm.ToString()].ColumnName = "EmailAddress"; } toMails.AddRange(seedList.Tables[0].AsEnumerable().Select(row => row.Field<string>("EMailAddress")).ToArray()); } toMails.AddRange(pToAddress.Split(',')); if (toMails.Count > 0) { message.To.Add(new MailAddress(toMails[0].ToString())); if (toMails.Count > 1) { toMails.RemoveAt(0); foreach (string mailid in toMails) message.Bcc.Add(new MailAddress(mailid)); } } if (pReplyAddress != string.Empty) message.ReplyTo = new MailAddress(pReplyAddress.ToString());// pReplyAddress; if (pSubject.Equals("Report")) message.Subject = pSubject; else message.Subject = "Test Mailing: " + pSubject; message.Body = pBody; message.IsBodyHtml = true; Configuration configurationFile = WebConfigurationManager.OpenWebConfiguration("~/Web.config"); MailSettingsSectionGroup mailSettings = configurationFile.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup; if (mailSettings != null) { port = mailSettings.Smtp.Network.Port; host = mailSettings.Smtp.Network.Host; password = mailSettings.Smtp.Network.Password; username = mailSettings.Smtp.Network.UserName; } SmtpClient emailClient = new SmtpClient(host); System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(username, password); emailClient.UseDefaultCredentials = false; emailClient.Credentials = SMTPUserInfo; emailClient.Send(message); EMailErrorMessage = String.Empty; return true; #endregion } else { #region Email code using server smtp protocol System.Web.Mail.MailMessage mAffMessage = new System.Web.Mail.MailMessage(); mAffMessage.From = pFromAddress; mAffMessage.BodyFormat = System.Web.Mail.MailFormat.Html; if (pIsMultipleRecipients) mAffMessage.Bcc = pToAddress; else mAffMessage.To = pToAddress; mAffMessage.Body = pBody; mAffMessage.Headers.Add("Reply-To", pReplyAddress.ToString()); mAffMessage.Subject = "Test Mailing: " + pSubject; System.Web.Mail.SmtpMail.SmtpServer = ConfigurationManager.AppSettings["SMTPServer"]; System.Web.Mail.SmtpMail.Send(mAffMessage); EMailErrorMessage = String.Empty; return true; #endregion } } catch (Exception ex) { EMailErrorMessage = ex.Message; return false; } }
public ActionResult Feedback(FormCollection collection) { JsonMessage jm = new JsonMessage(); try { string system = collection["system"]; string name = collection["name"]; string phone = collection["phone"]; string email = collection["email"]; string message = collection["message"]; string subject = "Запись на замер c сайта demyr"; string body = "Система: " + system + "\n"; body += "Имя: " + name + "\n"; body += "Телефон: " + phone + "\n"; body += "Email: " + email + "\n"; if (message != null) { body += "Сообщение: " + message + "\n"; } if (Convert.ToBoolean(ConfigurationManager.AppSettings["UseAgavaMail"])) { //1 MailMessage mailObj = new MailMessage(); mailObj.From = new MailAddress(ConfigurationManager.AppSettings["messageFrom"]); mailObj.To.Add(ConfigurationManager.AppSettings["messageTo"]); mailObj.Subject = subject; mailObj.Body = body; SmtpClient SMTPServer = new SmtpClient("localhost"); SMTPServer.Send(mailObj); //2 if (!String.IsNullOrWhiteSpace(email)) { MailMessage mailObj2 = new MailMessage(); mailObj2.From = new MailAddress(ConfigurationManager.AppSettings["messageFrom"]); mailObj2.To.Add(email); mailObj2.Subject = "Облако. Благодарим Вас за обращение в нашу компанию"; string filename = Server.MapPath("/Content/themes/ictec/templates/mail.htm"); if (System.IO.File.Exists(filename)) { using (StreamReader sr = new StreamReader(filename)) { mailObj2.Body = sr.ReadToEnd(); }; mailObj2.IsBodyHtml = true; SMTPServer.Send(mailObj2); } } } else { System.Web.Mail.MailMessage mail = new System.Web.Mail.MailMessage(); string SMTP_SERVER = "http://schemas.microsoft.com/cdo/configuration/smtpserver"; string SMTP_SERVER_PORT = "http://schemas.microsoft.com/cdo/configuration/smtpserverport"; string SEND_USING = "http://schemas.microsoft.com/cdo/configuration/sendusing"; string SMTP_USE_SSL = "http://schemas.microsoft.com/cdo/configuration/smtpusessl"; string SMTP_AUTHENTICATE = "http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"; string SEND_USERNAME = "******"; string SEND_PASSWORD = "******"; mail.Fields[SMTP_SERVER] = ConfigurationManager.AppSettings["SMTP"]; mail.Fields[SMTP_SERVER_PORT] = 465; mail.Fields[SEND_USING] = 2; mail.Fields[SMTP_USE_SSL] = true; mail.Fields[SMTP_AUTHENTICATE] = 1; mail.Fields[SEND_USERNAME] = ConfigurationManager.AppSettings["SMTP_login"]; mail.Fields[SEND_PASSWORD] = ConfigurationManager.AppSettings["SMTP_password"]; mail.From = ConfigurationManager.AppSettings["messageFrom"]; mail.To = ConfigurationManager.AppSettings["messageTo"]; mail.Subject = subject; mail.BodyFormat = System.Web.Mail.MailFormat.Text; mail.Body = body; System.Web.Mail.SmtpMail.SmtpServer = ConfigurationManager.AppSettings["SMTP"] + ":465"; System.Web.Mail.SmtpMail.Send(mail); } jm.Result = true; jm.Message = "Мы получили Ваш запрос и скоро свяжемся с Вами..."; } catch (Exception e) { jm.Result = true; jm.Message = "Во время отправки произошла ошибка - " + e.ToString(); } return Json(jm); }
/// <summary> /// 发送 /// </summary> /// <returns></returns> public bool Send() { #if NET1 System.Web.Mail.MailMessage myEmail = new System.Web.Mail.MailMessage(); myEmail.BodyEncoding = Encoding.GetEncoding("utf-8"); myEmail.From = this.From; myEmail.To = this._recipient; myEmail.Subject = this.Subject; myEmail.Body = this.Body; myEmail.Priority = System.Web.Mail.MailPriority.Normal; myEmail.BodyFormat = this.Html?System.Web.Mail.MailFormat.Html:System.Web.Mail.MailFormat.Text; //邮件形式,.Text、.Html // 通过SMTP服务器验证 myEmail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); myEmail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", this.MailServerUserName); myEmail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpaccountname",this.MailServerUserName); myEmail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", this.MailServerPassWord); myEmail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/postusername",this.RecipientName); myEmail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport",this.MailDomainPort); //当不是25端口(gmail:587) if(this.MailDomainPort != 25) { myEmail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true"); } System.Web.Mail.SmtpMail.SmtpServer = this.MailDomain; try { System.Web.Mail.SmtpMail.Send(myEmail); } catch { } return true; #else System.Net.Mail.MailMessage myEmail = new System.Net.Mail.MailMessage(); Encoding eEncod = Encoding.GetEncoding("utf-8"); myEmail.From = new System.Net.Mail.MailAddress(this.From, this.Subject, eEncod); myEmail.To.Add(this._recipient); myEmail.Subject = this.Subject; myEmail.IsBodyHtml = true; myEmail.Body = this.Body; myEmail.Priority = System.Net.Mail.MailPriority.Normal; myEmail.BodyEncoding = Encoding.GetEncoding("utf-8"); //myEmail.BodyFormat = this.Html?MailFormat.Html:MailFormat.Text; //邮件形式,.Text、.Html System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(); smtp.Host = this.MailDomain; smtp.Port = this.MailDomainPort; smtp.Credentials = new System.Net.NetworkCredential(this.MailServerUserName, this.MailServerPassWord); //smtp.UseDefaultCredentials = true; //smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; //当不是25端口(gmail:587) if (this.MailDomainPort != 25) { smtp.EnableSsl = true; } //System.Web.Mail.SmtpMail.SmtpServer = this.MailDomain; try { smtp.Send(myEmail); } catch (System.Net.Mail.SmtpException e) { string result = e.Message; return false; } return true; #endif }
/// <summary> /// 发送EMAIL /// </summary> /// <example> /// <code> /// Email _Email = new Email(); /// _Email.FromEmail = "*****@*****.**"; /// _Email.Subject = "<div>aaaa</div>"; /// _Email.Body = "aaaaaaaaaaaaa"; /// _Email.SmtpServer = "smtp.163.com"; /// _Email.SmtpUserName = "******"; /// _Email.SmtpPassword = "******"; /// _Email.Send("*****@*****.**"); /// </code> /// </example> /// <param name="toEmail">收信人 接收方地址</param> /// <returns>成功否</returns> public bool SmtpMailSend(string toEmail) { lock (lockHelper) { System.Web.Mail.MailMessage msg = new System.Web.Mail.MailMessage(); try { msg.From = _FromEmail;//发送方地址(如[email protected]) msg.To = toEmail;//接收方地址 msg.BodyFormat = _Format;//正文内容类型 msg.BodyEncoding = _Encoding;//正文内容编码 msg.Subject = _Subject;//主题 msg.Body = _Body;//内容 msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");//设置为需要用户验证 if (!_SmtpPort.Equals("25")) msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", _SmtpPort);//设置端口 msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", _SmtpUserName);//设置验证用户名 msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", _SmtpPassword);//设置验证密码 System.Web.Mail.SmtpMail.SmtpServer = _SmtpServer;//邮件服务器地址(如smtp.163.com) System.Web.Mail.SmtpMail.Send(msg);//发送 return true; } catch { } finally { } } return false; }
/// <summary> /// /// </summary> private System.String SendMail( anmar.SharpWebMail.EmailServerInfo server ) { System.String message = null; System.Web.Mail.SmtpMail.SmtpServer = server.Host; System.Web.Mail.MailMessage mailMessage = new System.Web.Mail.MailMessage(); mailMessage.To = this.toemail.Value; mailMessage.From = System.String.Format("{0} <{1}>", this.fromname.Value, this.GetFromAddress()); mailMessage.Subject = this.subject.Value.Trim(); System.String format = Request.Form["format"]; if ( format!=null && format.Equals("html") ) { mailMessage.BodyFormat = System.Web.Mail.MailFormat.Html; mailMessage.Body = bodyStart + FCKEditor.Value + bodyEnd; } else { mailMessage.BodyFormat = System.Web.Mail.MailFormat.Text; mailMessage.Body = FCKEditor.Value; } if ( this._headers != null ) { // RFC 2822 3.6.4. Identification fields if ( this._headers["Message-ID"]!=null ) { mailMessage.Headers["In-Reply-To"] = this._headers["Message-ID"]; mailMessage.Headers["References"] = this._headers["Message-ID"]; } if ( this._headers["References"]!=null ) { mailMessage.Headers["References"] = System.String.Concat (this._headers["References"], " ", mailMessage.Headers["References"]).Trim(); } else if ( this._headers["In-Reply-To"]!=null && this._headers["In-Reply-To"].IndexOf('>')==this._headers["In-Reply-To"].LastIndexOf('>') ) { mailMessage.Headers["References"] = System.String.Concat (this._headers["In-Reply-To"], " ", mailMessage.Headers["References"]).Trim(); } } mailMessage.Headers["X-Mailer"] = System.String.Format ("{0} {1}", Application["product"], Application["version"]); this.ProcessMessageAttachments(mailMessage); try { if ( log.IsDebugEnabled) log.Error ( "Sending message" ); System.Web.Mail.SmtpMail.Send(mailMessage); if ( log.IsDebugEnabled) log.Error ( "Message sent" ); } catch (System.Exception e) { message = e.Message; #if DEBUG && !MONO message += ". <br>InnerException: " + e.InnerException.Message; #endif if ( log.IsErrorEnabled ) log.Error ( "Error sending message", e ); if ( log.IsErrorEnabled ) log.Error ( "Error sending message (InnerException)", e.InnerException ); } mailMessage = null; return message; }
public ActionResult Feedback(FormCollection collection) { JsonMessage jm = new JsonMessage(); try { string receiver = collection["receiver"]; string message = collection["message"]; string body = "Куда ответить: " + receiver + "\n"; string subject = "Запрос"; if (message != null) { body += "Сообщение: " + message + "\n"; } if (Convert.ToBoolean(ConfigurationManager.AppSettings["UseAgavaMail"])) { //1 MailMessage mailObj = new MailMessage(); mailObj.From = new MailAddress(ConfigurationManager.AppSettings["messageFrom"]); mailObj.To.Add(ConfigurationManager.AppSettings["messageTo"]); mailObj.Subject = subject; mailObj.Body = body; SmtpClient SMTPServer = new SmtpClient("localhost"); SMTPServer.Send(mailObj); //2 MailMessage mailObj2 = new MailMessage(); mailObj2.From = new MailAddress(ConfigurationManager.AppSettings["messageFrom"]); mailObj2.To.Add(receiver); mailObj2.Subject = "Ваше сообщение, отправленное с сайта ReadyMade зарегистрировано"; string filename = Server.MapPath("/Content/Templates/mail.htm"); if (System.IO.File.Exists(filename)) { using (StreamReader sr = new StreamReader(filename)) { mailObj2.Body = sr.ReadToEnd(); mailObj2.Body = mailObj2.Body.Replace("[%текст%]", message); }; mailObj2.IsBodyHtml = true; SMTPServer.Send(mailObj2); } } else { System.Web.Mail.MailMessage mail = new System.Web.Mail.MailMessage(); string SMTP_SERVER = "http://schemas.microsoft.com/cdo/configuration/smtpserver"; string SMTP_SERVER_PORT = "http://schemas.microsoft.com/cdo/configuration/smtpserverport"; string SEND_USING = "http://schemas.microsoft.com/cdo/configuration/sendusing"; string SMTP_USE_SSL = "http://schemas.microsoft.com/cdo/configuration/smtpusessl"; string SMTP_AUTHENTICATE = "http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"; string SEND_USERNAME = "******"; string SEND_PASSWORD = "******"; mail.Fields[SMTP_SERVER] = ConfigurationManager.AppSettings["SMTP"]; mail.Fields[SMTP_SERVER_PORT] = 465; mail.Fields[SEND_USING] = 2; mail.Fields[SMTP_USE_SSL] = true; mail.Fields[SMTP_AUTHENTICATE] = 1; mail.Fields[SEND_USERNAME] = ConfigurationManager.AppSettings["SMTP_login"]; mail.Fields[SEND_PASSWORD] = ConfigurationManager.AppSettings["SMTP_password"]; mail.From = ConfigurationManager.AppSettings["messageFrom"]; mail.To = ConfigurationManager.AppSettings["messageTo"]; mail.Subject = subject; mail.BodyFormat = System.Web.Mail.MailFormat.Text; mail.Body = body; System.Web.Mail.SmtpMail.SmtpServer = ConfigurationManager.AppSettings["SMTP"] + ":465"; System.Web.Mail.SmtpMail.Send(mail); } jm.Result = true; jm.Message = "Спасибо, запрос отправлен. Ожидайте ответ."; } catch (Exception e) { jm.Result = true; jm.Message = "Во время отправки произошла ошибка - " + e.ToString(); } return Json(jm); }
public ActionResult FeedbackRequest(FormCollection collection) { JsonMessage jm = new JsonMessage(); try { string name = collection["name"]; string phone = collection["phone"]; string email = collection["email"]; string body = "Куда ответить: " + phone + " (" + name + ")" + "\n"; string subject = "Запрос обратной связи c " + HttpContext.Request.Url.Authority; if (email != null) { body += "Email: " + email + "\n"; } if (Convert.ToBoolean(ConfigurationManager.AppSettings["UseAgavaMail"])) { MailMessage mailObj = new MailMessage(); mailObj.From = new MailAddress(ConfigurationManager.AppSettings["messageFrom"]); mailObj.To.Add(ConfigurationManager.AppSettings["messageTo"]); mailObj.Subject = subject; mailObj.Body = body; SmtpClient SMTPServer = new SmtpClient("localhost"); SMTPServer.Send(mailObj); } else { System.Web.Mail.MailMessage mail = new System.Web.Mail.MailMessage(); string SMTP_SERVER = "http://schemas.microsoft.com/cdo/configuration/smtpserver"; string SMTP_SERVER_PORT = "http://schemas.microsoft.com/cdo/configuration/smtpserverport"; string SEND_USING = "http://schemas.microsoft.com/cdo/configuration/sendusing"; string SMTP_USE_SSL = "http://schemas.microsoft.com/cdo/configuration/smtpusessl"; string SMTP_AUTHENTICATE = "http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"; string SEND_USERNAME = "******"; string SEND_PASSWORD = "******"; mail.Fields[SMTP_SERVER] = ConfigurationManager.AppSettings["SMTP"]; mail.Fields[SMTP_SERVER_PORT] = 465; mail.Fields[SEND_USING] = 2; mail.Fields[SMTP_USE_SSL] = true; mail.Fields[SMTP_AUTHENTICATE] = 1; mail.Fields[SEND_USERNAME] = ConfigurationManager.AppSettings["SMTP_login"]; mail.Fields[SEND_PASSWORD] = ConfigurationManager.AppSettings["SMTP_password"]; mail.From = ConfigurationManager.AppSettings["messageFrom"]; mail.To = ConfigurationManager.AppSettings["messageTo"]; mail.Subject = subject; mail.BodyFormat = System.Web.Mail.MailFormat.Text; mail.Body = body; System.Web.Mail.SmtpMail.SmtpServer = ConfigurationManager.AppSettings["SMTP"] + ":465"; System.Web.Mail.SmtpMail.Send(mail); } jm.Result = true; jm.Message = "Спасибо, запрос отправлен. Ожидайте ответ."; } catch (Exception e) { jm.Result = true; jm.Message = "Во время отправки произошла ошибка - " + e.ToString(); } return Json(jm); }