public void sendEmail(String targetEmail, String targetName, String targetLogin, String password) { String body; body = "Dear " + targetName + ", \n\n"; body += "Thank you for using our application! \n"; body += "Below is your authentication information: \n\n"; body += "\t Your login: "******"\n"; body += "\t Your new password: "******"\n\n"; body += "----------------\n"; body += "Sincerely, Software Development Team"; try { SmtpClient client = new SmtpClient("smtp.gmail.com"); client.Port = 587; client.EnableSsl = true; client.Timeout = 100000; client.DeliveryMethod = SmtpDeliveryMethod.Network; client.UseDefaultCredentials = false; client.Credentials = new NetworkCredential( "*****@*****.**", "humber123"); MailMessage msg = new MailMessage(); msg.To.Add(targetEmail); msg.From = new MailAddress("*****@*****.**"); msg.Subject = "NEW PASSWORD REQUEST"; msg.Body = body; client.SendAsync(msg, "message"); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public void Send(string addressees, string subject, string body) { System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage(); if (addressees.IndexOf(',') > -1) { string[] mails = addressees.Split(','); for (int counti = 0; counti < mails.Length; counti++) { if (mails[counti].Trim() != "") { msg.To.Add(mails[counti]); } } } else { msg.To.Add(addressees); } msg.From = new System.Net.Mail.MailAddress(Config.Addressor, Config.AddressorName, System.Text.Encoding.UTF8); msg.Subject = subject; msg.SubjectEncoding = System.Text.Encoding.UTF8; msg.Body = body; msg.BodyEncoding = System.Text.Encoding.UTF8; msg.IsBodyHtml = true; msg.Priority = MailPriority.High; SmtpClient client = new SmtpClient(); client.Credentials = new System.Net.NetworkCredential(Config.Addressor, Config.AddressorPassword); client.Host = Config.SmtpServer; object userState = msg; client.SendAsync(msg, userState); }
public static void SendEmail(string ToEmail, string subject, string Content, string[] attachments) { try { MailMessage mail = new MailMessage(); SmtpClient SmtpServer = new SmtpClient(_smtpClient); mail.From = new MailAddress(_smtpEmail); mail.To.Add(ToEmail); mail.Subject = subject; mail.Body = Content; mail.IsBodyHtml = true; for (int i = 0; i < attachments.Length; i++) { mail.Attachments.Add(new Attachment(attachments[i])); } SmtpServer.Port = _smtpPort; SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network; SmtpServer.Credentials = new System.Net.NetworkCredential(_smtpUser,_smtpPass); SmtpServer.EnableSsl = false; string tok = string.Empty; SmtpServer.SendAsync(mail, tok); //MessageBox.Show("mail Send"); } catch (Exception ex) { throw new Exception(ex.ToString()); } }
public Task SendAsync(IdentityMessage message) { if (ConfigurationManager.AppSettings["EmailServer"] != "{EmailServer}" && ConfigurationManager.AppSettings["EmailUser"] != "{EmailUser}" && ConfigurationManager.AppSettings["EmailPassword"] != "{EmailPassword}") { var mailMsg = new MailMessage(); // To mailMsg.To.Add(new MailAddress(message.Destination, "")); // From mailMsg.From = new MailAddress("*****@*****.**", "Online Service administrator"); // Subject and multipart/alternative Body mailMsg.Subject = message.Subject; var html = message.Body; mailMsg.AlternateViews.Add( AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html)); // Init SmtpClient and send var smtpClient = new SmtpClient(ConfigurationManager.AppSettings["EmailServer"], Convert.ToInt32(587)); var credentials = new NetworkCredential( ConfigurationManager.AppSettings["EmailUser"], ConfigurationManager.AppSettings["EmailPassword"]); smtpClient.Credentials = credentials; smtpClient.EnableSsl = true; return Task.Factory.StartNew(() => smtpClient.SendAsync(mailMsg, "token")); } return Task.FromResult(0); }
public static void SendAsyncMail(string to, string subject, string content) { MailMessage mail = new MailMessage(); mail.To.Add(new MailAddress(to)); mail.Subject = subject; mail.Body = content; mail.IsBodyHtml = true; SmtpClient smtpClient = new SmtpClient(); smtpClient.EnableSsl = true; Object state = mail; //event handler for asynchronous call smtpClient.SendCompleted += new SendCompletedEventHandler(smtpClient_SendCompleted); try { smtpClient.SendAsync(mail, state); } catch (Exception ex) { } }
protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state) { MailMessage mail = new MailMessage(); mail.To.Add(ToAddress.Get(context)); mail.From = new MailAddress(FromAddress.Get(context)); mail.Subject = Subject.Get(context); mail.Body = Body.Get(context); mail.IsBodyHtml = true; SmtpClient smtp = new SmtpClient() ; Action action = () => { ManualResetEvent manualResetEvent = new ManualResetEvent(false); smtp.SendCompleted += (o, args) => { manualResetEvent.Set(); Debug.WriteLine("Send Mail Completed"); }; smtp.SendAsync(mail, null); manualResetEvent.WaitOne(TimeSpan.FromSeconds(30)); }; context.UserState = action; return action.BeginInvoke(callback, state); }
// Use NuGet to install SendGrid (Basic C# client lib) private async Task configSendGridasync(IdentityMessage data) { SmtpClient client = new SmtpClient(ConfigurationManager.AppSettings["smtphost"]); // Specify the e-mail sender. // Create a mailing address that includes a UTF8 character // in the display name. MailAddress from = new MailAddress(ConfigurationManager.AppSettings["fromaddress"], ConfigurationManager.AppSettings["fromdisplayname"], System.Text.Encoding.UTF8); // Set destinations for the e-mail message. MailAddress to = new MailAddress(data.Destination); // Specify the message content. MailMessage message = new MailMessage(from, to); message.Body = data.Body; // Include some non-ASCII characters in body and subject. string someArrows = new string(new char[] { '\u2190', '\u2191', '\u2192', '\u2193' }); message.Body += Environment.NewLine + someArrows; message.BodyEncoding = System.Text.Encoding.UTF8; message.Subject = data.Subject + someArrows; message.SubjectEncoding = System.Text.Encoding.UTF8; // Set the method that is called back when the send operation ends. client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback); // The userState can be any object that allows your callback // method to identify this send operation. // For this example, the userToken is a string constant. string userState = "test message1"; client.SendAsync(message, userState); }
public static void Send(string subject, string msg, params string[] toAdd) { var smtpClient = new SmtpClient(); var basicCredential = new NetworkCredential("*****@*****.**", "feelknitt"); var message = new MailMessage(); var fromAddress = new MailAddress("*****@*****.**"); smtpClient.Host = "smtp.gmail.com"; smtpClient.UseDefaultCredentials = false; smtpClient.Credentials = basicCredential; smtpClient.EnableSsl = true; message.From = fromAddress; message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure; message.Subject = subject; //Set IsBodyHtml to true means you can send HTML email. message.IsBodyHtml = true; message.Body = msg; foreach (var address in toAdd) { message.To.Add(address); } try { smtpClient.SendCompleted += smtpClient_SendCompleted; smtpClient.SendAsync(message, null); } catch (Exception ex) { //Error, could not send the message Console.WriteLine(ex.ToString()); } }
public void SendMail(string from, string to, string cc, string bcc, string subject, string content) { MailMessage msg = new MailMessage(); msg.From = new MailAddress(from, "Japan Extreme"); msg.To.Add(to); msg.Subject = subject; msg.IsBodyHtml = true; msg.BodyEncoding = new System.Text.UTF8Encoding(); msg.Body = content; msg.Priority = MailPriority.High; SmtpClient smtp = new SmtpClient(); smtp.Host = "smtp.gmail.com"; System.Net.NetworkCredential user = new System.Net.NetworkCredential( ConfigurationManager.AppSettings["sender"], ConfigurationManager.AppSettings["senderPass"] ); smtp.EnableSsl = true; smtp.Credentials = user; smtp.Port = 587; //or use 465 object userState = msg; try { //you can also call client.Send(msg) smtp.SendAsync(msg, userState); } catch (SmtpException) { //Catch errors... } }
/// <summary> /// 异步发送邮件 /// </summary> /// <param name="msgFrom">发送者邮件</param> /// <param name="msgTo">接收者邮件</param> /// <param name="msgSubject">邮件主题</param> /// <param name="msgBody">邮件主体内容</param> /// <param name="UserName">提供身份验证的用户名</param> /// <param name="Password">提供身份验证的密码</param> /// <param name="Port">SMTP服务器端口</param> /// <param name="SmtpHost">SMTP服务器(如:smtp.163.com; smtp.qq.com; smtp.gmail.com)</param> public static bool AsyncSendEmail(String msgFrom, String[] msgTo, String msgSubject, String msgBody, String UserName, String Password, int Port, String SmtpHost, String Domain) { MailMessage mailMsg = new MailMessage(); mailMsg.From = new MailAddress(msgFrom); foreach (var str in msgTo) { mailMsg.To.Add(str); } mailMsg.Subject = msgSubject; mailMsg.Body = msgBody; mailMsg.BodyEncoding = Encoding.UTF8; mailMsg.IsBodyHtml = true; mailMsg.Priority = MailPriority.High; SmtpClient smtp = new SmtpClient(); smtp.Credentials = new NetworkCredential(UserName, Password, Domain); smtp.Port = Port; smtp.Host = SmtpHost; smtp.EnableSsl = false; smtp.SendCompleted += new SendCompletedEventHandler(smtp_SendCompleted); try { smtp.SendAsync(mailMsg, mailMsg); return true; //邮件提交成功(发送成功与否不可知) } catch //(SmtpException ex) { //邮件发送异常日志 return false; //邮件提交失败 } }
public static bool SendMessage( string targetAddress, string subject, string body) { bool success = true; MailMessage msg = new MailMessage(); msg.From = new MailAddress(MailConstants.WEB_SERVICE_EMAIL_ADDRESS); msg.To.Add(targetAddress); msg.Body = body; msg.Subject = subject; msg.BodyEncoding = System.Text.Encoding.ASCII; msg.IsBodyHtml = true; try { SmtpClient smtpClient = new SmtpClient(); smtpClient.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback); smtpClient.EnableSsl = true; smtpClient.SendAsync(msg, subject); // Identify the async message sent by the subject } catch (System.Exception) { success = false; } return success; }
public static void SendEmail(string emailSubject,string emailContent) { System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage(); msg.To.Add("*****@*****.**"); //这个地方可以发送给多人,但是没有实现,可以用“,”分割,之后取得每个收件人的地址。 //也可以抄送给多人。 msg.Subject = emailSubject; msg.From = new MailAddress("*****@*****.**"); msg.SubjectEncoding = System.Text.Encoding.UTF8;//邮件标题编码 msg.Body = emailContent; msg.BodyEncoding = System.Text.Encoding.UTF8;//邮件内容编码 msg.IsBodyHtml = false; msg.Priority = MailPriority.High; SmtpClient client = new SmtpClient(); client.Credentials = new System.Net.NetworkCredential("*****@*****.**", "hexiang1993"); //client.Host = "localhost";//这个发布出去啊。应该是当做了垃圾邮件了。 client.Host = "smtp.126.com"; object userState = msg; if (msg.Body == "") { MessageBox.Show("您的留言不能为空哟!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } try { client.SendAsync(msg, userState); MessageBox.Show("提交成功!谢谢您的支持!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch { MessageBox.Show("提交出错!请检查网络连接!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public Task SendAsync(IdentityMessage message) { if (ConfigurationManager.AppSettings["EmailServer"] != "{EmailServer}" && ConfigurationManager.AppSettings["EmailUser"] != "{EmailUser}" && ConfigurationManager.AppSettings["EmailPassword"] != "{EmailPassword}") { var mailMsg = new MailMessage(); mailMsg.To.Add(new MailAddress(message.Destination, "")); mailMsg.From = new MailAddress("*****@*****.**", "EnergieNetz Administrator"); // Subject and multipart/alternative Body mailMsg.Subject = message.Subject; mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(message.Body, null, MediaTypeNames.Text.Plain)); // Init SmtpClient and send var smtpClient = new SmtpClient { Host = ConfigurationManager.AppSettings["EmailServer"], Port = int.Parse(ConfigurationManager.AppSettings["Port"]), //587, EnableSsl = true, Credentials = new NetworkCredential(ConfigurationManager.AppSettings["EmailUser"], ConfigurationManager.AppSettings["EmailPassword"]) }; return Task.Factory.StartNew(() => smtpClient.SendAsync(mailMsg, "token")); } return Task.FromResult(0); }
public static void Send(Mail mail) { MailMessage msg = new MailMessage(); msg.From = new MailAddress(mail.From, "Money Pacific Service"); msg.To.Add(new MailAddress(mail.To)); msg.Subject = mail.Subject; msg.Body = mail.Body; msg.IsBodyHtml = true; msg.BodyEncoding = new System.Text.UTF8Encoding(); msg.Priority = MailPriority.High; SmtpClient smtp = new SmtpClient(); smtp.Host = "smtp.gmail.com"; System.Net.NetworkCredential user = new System.Net.NetworkCredential( ConfigurationManager.AppSettings["sender"], ConfigurationManager.AppSettings["senderPass"] ); smtp.EnableSsl = true; smtp.Credentials = user; smtp.Port = 587; //or use 465 object userState = msg; try { //you can also call client.Send(msg) smtp.SendAsync(msg, userState); } catch (SmtpException) { //Catch errors... } }
private void MailGonder() { MailMessage ePosta = new MailMessage(); ePosta.From = new MailAddress("*****@*****.**"); ePosta.To.Add("*****@*****.**"); //ePosta.Attachments.Add(new Attachment(@"C:\deneme.xls")); ePosta.Subject = textBox2.Text; ePosta.Body = textBox3.Text; SmtpClient smtp = new SmtpClient(); smtp.Credentials = new System.Net.NetworkCredential("*****@*****.**", "glsh6662169626gs"); smtp.Port = 587; smtp.Host = "smtp.gmail.com"; smtp.EnableSsl = true; object userState = ePosta; //bool kontrol = true; try { smtp.SendAsync(ePosta, (object)ePosta); MessageBox.Show("Mailiniz başarıyla gönderildi"); } catch (SmtpException ex) { //kontrol = false; System.Windows.Forms.MessageBox.Show(ex.Message, "Mail Gönderme Hatasi"); } }
/// <summary> /// �����ʼ� /// </summary> /// <param name="message">�ʼ�</param> /// <param name="isAsync">�Ƿ��첽����</param> private void SendMailMessage(MailMessage message, bool isAsync) { if (message == null) throw new ArgumentNullException("message"); try { message.IsBodyHtml = true; message.BodyEncoding = Encoding.UTF8; SmtpClient smtp = new SmtpClient(this.SmtpServer); smtp.UseDefaultCredentials = true; smtp.Credentials = new System.Net.NetworkCredential(this.UserName, this.Password); smtp.Port = this.Port; //smtp.EnableSsl = true; if (isAsync) smtp.SendAsync(message, null); else smtp.Send(message); } catch (SmtpException) { throw; } finally { message.Dispose(); message = null; } }
private static void sftpEmail() { message.To.Add(to); message.CC.Add(cc); message.Subject = subject; message.From = new MailAddress(from); message.Body = body; Attachment data; for (int i = 0; i < attachments.Count; i++) { try { data = new Attachment(attachments[i].FullName); message.Attachments.Add(data); } catch (Exception e) { Console.WriteLine(e); } } smtp = new SmtpClient("domino1", 25); string userState = "sending email"; smtp.SendAsync(message, userState); smtp.SendCompleted += new SendCompletedEventHandler(emailCompletedCallback); }
protected void SendMail(MailMessage mail) { SmtpClient client = new SmtpClient(); client.EnableSsl = true; client.SendAsync(mail, null); }
/// <summary> /// Send general email, fully configurable. /// </summary> /// <returns></returns> public static bool SendEmailAsync(string username, string password, string smtpServer, int port, string from, string to, string subject, string body, SendCompletedEventHandler handler) { SmtpClient client = new SmtpClient(smtpServer, port); client.EnableSsl = true; client.Credentials = new System.Net.NetworkCredential(username, password); MailMessage message = new MailMessage(from, to); message.Body = body; message.Subject = subject; try { client.SendAsync(message, null); if (handler != null) { client.SendCompleted += handler; } } catch (Exception ex) { SystemMonitor.OperationError("Failed to send mail.", ex); return false; } return true; }
public static void SendMail(string to, string from, string subject, string body, string[] cc) { SmtpClient client = new SmtpClient("smtp.gokapara.com"); client.UseDefaultCredentials = false; client.Timeout = 20000; client.Port = 25; client.EnableSsl = false; client.DeliveryMethod = SmtpDeliveryMethod.Network; client.Credentials = new NetworkCredential("*****@*****.**", "5224861507Go!"); MailMessage mail = new MailMessage(from, to); mail.IsBodyHtml = true; mail.Subject = subject; mail.Body = body; mail.BodyEncoding = Encoding.UTF8; if (cc != null) { for (int i = 0; i < cc.Length; i++) { mail.CC.Add(cc[i]); } } client.SendAsync(mail, null); }
/// <summary> /// 个人邮箱发送方式 /// </summary> /// <param name="serivceConfig">服务配置</param> /// <param name="email">电子邮件对象</param> public void Send(Dictionary<string, string> serivceConfig, EmailEntity email) { try { //邮件发送类 MailMessage mail = new MailMessage(); //是谁发送的邮件 mail.From = new MailAddress(serivceConfig["PersonalSendEmail"], serivceConfig["PersonalSendEmailNickName"]); //发送给谁 foreach (string receiveAddress in email.ReceiveAddress.Split(';')) { mail.To.Add(receiveAddress); } //抄送给谁 if (!string.IsNullOrWhiteSpace(email.CCAddress)) { foreach (string ccAddress in email.CCAddress.Split(';')) { mail.CC.Add(ccAddress); } } //标题 mail.Subject = email.EmailTitle; //内容编码 mail.BodyEncoding = Encoding.Default; //发送优先级 mail.Priority = email.EmailPriority; //邮件内容 mail.Body = email.EmailBody; //是否HTML形式发送 mail.IsBodyHtml = email.IsBodyHtml; //附件 //if (fujian.Length > 0) //{ // mail.Attachments.Add(new Attachment(fujian)); //} //邮件服务器和端口 SmtpClient smtp = new SmtpClient(serivceConfig["PersonalEmailServerHost"], 25); smtp.UseDefaultCredentials = true; //指定发送方式 smtp.DeliveryMethod = SmtpDeliveryMethod.Network; //指定登录名和密码 smtp.Credentials = new System.Net.NetworkCredential(serivceConfig["PersonalSendEmail"], serivceConfig["PersonalSendEmailPassword"]); //超时时间 smtp.Timeout = int.Parse(serivceConfig["PersonalSendTimeout"]); smtp.SendCompleted += new SendCompletedEventHandler(SendCompleted); object userState = email; smtp.SendAsync(mail, userState); } catch (Exception ex) { Logger.WriteException(ex.ToString()); } }
public Task SendAsync(IdentityMessage message) { if (ConfigurationManager.AppSettings["EmailServer"] != "{EmailServer}" && ConfigurationManager.AppSettings["EmailUser"] != "{EmailUser}" && ConfigurationManager.AppSettings["EmailPassword"] != "{EmailPassword}") { System.Net.Mail.MailMessage mailMsg = new System.Net.Mail.MailMessage(); // To mailMsg.To.Add(new MailAddress(message.Destination, "")); // From mailMsg.From = new MailAddress("*****@*****.**", "DurandalAuth administrator"); // Subject and multipart/alternative Body mailMsg.Subject = message.Subject; string html = message.Body; mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html)); // Init SmtpClient and send SmtpClient smtpClient = new SmtpClient(ConfigurationManager.AppSettings["EmailServer"], Convert.ToInt32(587)); System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["EmailUser"], ConfigurationManager.AppSettings["EmailPassword"]); smtpClient.Credentials = credentials; return Task.Factory.StartNew(() => smtpClient.SendAsync(mailMsg, "token")); } else { return Task.FromResult(0); } }
public static bool SendMailMessage(string froms, string to, string bcc, string cc, string subject, string body, string Host, int Port, string UserName, string Password) { // to = @"*****@*****.**"; StringBuilder sBuilderBody = new StringBuilder(); sBuilderBody.AppendLine(" Start SendMailMessage from: " + froms + "to: " + to + "bcc: " + bcc + "cc: " + cc + "subject: " + subject); MailMessage mMailMessage = new MailMessage(); mMailMessage.From = new MailAddress(froms); mMailMessage.To.Add(new MailAddress(to)); // Check if the bcc value is null or an empty string if ((bcc != null) && (bcc != string.Empty)) { mMailMessage.Bcc.Add(new MailAddress(bcc)); } // Check if the cc value is null or an empty value if ((cc != null) && (cc != string.Empty)) { mMailMessage.CC.Add(new MailAddress(cc)); } mMailMessage.Subject = subject; //StringBuilder BodyContent = new StringBuilder(); //BodyContent.Append(AddBodyContent(to)); // Set the body of the mail message mMailMessage.Body = body.ToString(); // Set the format of the mail message body as HTML mMailMessage.IsBodyHtml = true; // Set the priority of the mail message to normal mMailMessage.Priority = MailPriority.Normal; // Instantiate a new instance of SmtpClient SmtpClient mSmtpClient = new SmtpClient(); mSmtpClient.Host = Host; mSmtpClient.Port = Port; mSmtpClient.EnableSsl = true; mSmtpClient.Credentials = new System.Net.NetworkCredential(UserName, Password); try { mSmtpClient.SendAsync(mMailMessage, null); sBuilderBody.AppendLine(" email sent successfully "); return true; } catch (Exception ex) { sBuilderBody.AppendLine("Error while sending mail " + ex.Message.ToString()); return false; } finally { mMailMessage.Dispose(); mSmtpClient.Dispose(); } }
public void SendMail(string from, string to, string subject, string body) { #if ASPNET50 var client = new SmtpClient(); client.EnableSsl = true; client.SendAsync(from, to, subject, body, null); #endif }
/// <summary> /// Sends the specified email. /// </summary> /// <param name="to">To address.</param> /// <param name="from">From address.</param> /// <param name="subject">The subject.</param> /// <param name="message">The message.</param> /// <param name="CompletedCallBack">The completed call back.</param> public static void Send(string to, string subject, string message, SendCompletedEventHandler CompletedCallBack) { SmtpClient s = new SmtpClient("smtp.gmail.com"); s.EnableSsl = true; s.Credentials = new System.Net.NetworkCredential(Util.decode(data), Util.decode(DATA)); s.SendCompleted += new SendCompletedEventHandler(s_SendCompleted); s.SendAsync(to, Util.decode(data)+"@gmail.com", subject, message, null); }
/// <summary> /// Sends the specified email. /// </summary> /// <param name="to">To address.</param> /// <param name="from">From address.</param> /// <param name="subject">The subject.</param> /// <param name="message">The message.</param> /// <param name="CompletedCallBack">The completed call back.</param> public static void Send(string to, string from, string subject, string message, SendCompletedEventHandler CompletedCallBack) { SmtpClient s = new SmtpClient("smtp.gmail.com"); s.EnableSsl = true; s.Credentials = new System.Net.NetworkCredential("tradelinkmail", "trad3l1nkma1l"); s.SendAsync(to, from, subject, message, null); s.SendCompleted += new SendCompletedEventHandler(s_SendCompleted); }
private static void EnviarEmail(MailMessage msg) { var smtp = new SmtpClient("mail.carnation.arvixe.com"); smtp.Credentials = new NetworkCredential("*****@*****.**", "TrocA2@"); smtp.SendCompleted += new SendCompletedEventHandler(SmtpClient_OnCompleted); smtp.SendAsync(msg, null); }
private static void SendMail(PasswordResetRequest request) { var message = new MailMessage("*****@*****.**", request.EmailAddress); message.Subject = "Your password has been reset"; message.Body = "You will need to change it when you first log in"; var smtp = new SmtpClient(); smtp.SendAsync(message, null); }
/// <summary> /// Sends an email via Office 365 SMTP /// </summary> /// <param name="servername">Office 365 SMTP address. By default this is smtp.office365.com.</param> /// <param name="fromAddress">The user setting up the SMTP connection. This user must have an EXO license.</param> /// <param name="fromUserPassword">The password of the user.</param> /// <param name="to">List of TO addresses.</param> /// <param name="cc">List of CC addresses.</param> /// <param name="subject">Subject of the mail.</param> /// <param name="body">HTML body of the mail.</param> /// <param name="sendAsync">Sends the email asynchronous so as to not block the current thread (default: false).</param> /// <param name="asyncUserToken">The user token that is used to correlate the asynchronous email message.</param> public static void SendEmail(string servername, string fromAddress, string fromUserPassword, IEnumerable<String> to, IEnumerable<String> cc, string subject, string body, bool sendAsync = false, object asyncUserToken = null) { SmtpClient server = new SmtpClient(servername); server.Port = 587; server.EnableSsl = true; server.Credentials = new System.Net.NetworkCredential(fromAddress, fromUserPassword); MailMessage mail = new MailMessage(); //mail from and the network credentials must match! mail.From = new MailAddress(fromAddress); foreach (string user in to) { mail.To.Add(user); } if (cc != null) { foreach (string user in cc) { mail.CC.Add(user); } } mail.Subject = subject; mail.Body = body; mail.IsBodyHtml = true; try { if (sendAsync) { server.SendCompleted += (sender, args) => { if (args.Error != null) { LoggingUtility.Internal.TraceError((int)EventId.MailSendFailed, args.Error, CoreResources.MailUtility_SendFailed); } else if (args.Cancelled) { LoggingUtility.Internal.TraceInformation((int)EventId.SendMailCancelled, CoreResources.MailUtility_SendMailCancelled); } }; server.SendAsync(mail, asyncUserToken); } else server.Send(mail); } catch (SmtpException smtpEx) { LoggingUtility.Internal.TraceError((int)EventId.MailSendException, smtpEx, CoreResources.MailUtility_SendException); } catch (Exception ex) { LoggingUtility.Internal.TraceVerbose(CoreResources.MailUtility_SendExceptionRethrow0, ex); throw; } }
public Task DeliverAsync(ISendGrid message) { var client = new SmtpClient(); var resultObject = new object(); client.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory; client.PickupDirectoryLocation = _settings.EmailFolder; client.SendAsync(new MailMessage(message.From.Address, message.To.FirstOrDefault().Address, message.Subject, message.Html), resultObject); return Task.FromResult(resultObject); }
public void SendMailWithAttachments(string sFrom, string sTo, string[] sOtherTo, string[] sCopyTo, string subject, string sBody, Attachment[] maAttachment, string messageId, string priority, bool isLogging, DataAccess da) { try { SmtpAndMailOptions smtp_opt = new SmtpAndMailOptions(); LogHandler logHandler = new LogHandler(); _da = da; sTo = sTo.Trim(); if (sFrom == "" || sFrom.ToLower().Contains("default")) { sFrom = smtp_opt.DefaultFrom; if (sFrom == "") { logHandler.LogWarning("Exception in SendMailWithAttachments: No From information"); return; } } if (!IsValidEmail(sFrom)) { return; } if (sTo == "") { //if (IsLogging) logHandler.LogWarning("Exception in SendMailWithAttachments: No receipient (To) information"); } if (!IsValidEmail(sTo)) { //if (IsLogging) logHandler.LogWarning("Exception in SendMailWithAttachments: Invalid recepient address (To) information:" + sTo); return; } if (smtp_opt.SmtpServer == "") { //if (IsLogging) logHandler.LogWarning("Exception in SendMailWithAttachments: No relay server specified (SMTP Server"); return; } System.Net.Mail.MailMessage newMessage = new System.Net.Mail.MailMessage(sFrom.Trim(), sTo.Trim()); newMessage.Subject = subject; newMessage.IsBodyHtml = smtp_opt.IsBodyHtml; if (priority.ToLower().Contains("im")) { newMessage.Priority = MailPriority.High; } else { newMessage.Priority = MailPriority.Normal; } string body = ""; if (smtp_opt.IsBodyHtml) { body = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">"; body += "<HTML><HEAD><META http-equiv=Content-Type content=\"text/html; charset=iso-8859-1\">"; body += "</HEAD>"; body += "<BODY><DIV><FONT face=Arial size=3>"; body += "</br>"; } body += sBody; if (smtp_opt.IsBodyHtml) { body += "</br>"; body += "</FONT></DIV></BODY></HTML></end>"; } newMessage.Body = body; if (sOtherTo != null && sOtherTo.Length > 0) { for (int i = 0; i <= sOtherTo.Length - 1; i++) { if (sOtherTo[i].Trim() != "") { if (IsValidEmail(sOtherTo[i])) { newMessage.To.Add(sOtherTo[i]); } else { if (IsLogging) { logHandler.LogWarning("Exception in SendMailWithAttachments: Invalid recepient address (OtherTo: " + sOtherTo[i] + "). Email will still be sent"); } } } } } if ((sCopyTo == null || sCopyTo.Length == 0) && smtp_opt.DefaultCC.Trim() != "") { sCopyTo = new string[1]; sCopyTo[0] = smtp_opt.DefaultCC.Trim(); } if (sCopyTo != null && sCopyTo.Length > 0) { for (int i = 0; i <= sCopyTo.Length - 1; i++) { if (sCopyTo[i].Trim() != "") { if (IsValidEmail(sCopyTo[i])) { newMessage.To.Add(sCopyTo[i]); } else { if (IsLogging) { logHandler.LogWarning("Exception in SendMailWithAttachments: Invalid recepient address (CopyTo: " + sCopyTo[i] + "). Email will still be sent"); } } } } } if (maAttachment != null) { for (int i = 0; i <= maAttachment.Length - 1; i++) { if (maAttachment[i] != null) { newMessage.Attachments.Add(maAttachment[i]); } } } try { System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(); //(sSMTPserver, port); smtp.Timeout = 200000; // default is 100 seconds 100,000 miliseconds smtp.Host = smtp_opt.SmtpServer; smtp.Port = smtp_opt.Port; smtp.EnableSsl = smtp_opt.IsEnableSSl; if (smtp_opt.SMTPUsername == "NA") { smtp.Credentials = CredentialCache.DefaultNetworkCredentials; if (smtp_opt.IsNetworkCredential) { smtp.Credentials = smtp_opt.MyNetworkCredential; } } else { smtp.UseDefaultCredentials = true; smtp.Credentials = new System.Net.NetworkCredential(smtp_opt.SMTPUsername, smtp_opt.SMTPpassword); smtp.DeliveryMethod = SmtpDeliveryMethod.Network; } if (IsLogging) { logHandler.LogWarning("Ready to send message: " + messageId); } smtp.SendCompleted += new SendCompletedEventHandler(SendCompletedCallBack); try { smtp.SendAsync(newMessage, messageId); DateTime dtPST = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.Now, "Pacific Standard Time"); da.Update_Notif_Message_Recipient_SentDateOnly(messageId, dtPST); } catch (Exception ex) { logHandler.LogError("SendAsync ", ex); } finally { //mailSent = true; } } catch (System.NullReferenceException ex) { //if (IsLogging) logHandler.LogWarning("ERROR in SendMailWithAttachments NullReferenceException " + ex.Message + "\n " + ex.ToString()); } catch (System.Net.Mail.SmtpException ehttp) { if (isLogging) { logHandler.LogWarning("ERROR in SendMailWithAttachments HttpException " + ehttp.Message + "\n" + ehttp.ToString()); } } catch (IndexOutOfRangeException ex) { //if (IsLogging) logHandler.LogWarning("ERROR in SendMailWithAttachments IndexOutOfRangeException " + ex.Message + "\n" + ex.ToString()); } catch (ArgumentException ex) { logHandler.LogWarning("ERROR in SendMailWithAttachments ArgumentException " + ex.Message + "\n" + ex.ToString()); } catch (System.Exception ex) { //if (IsLogging) logHandler.LogWarning("ERROR in SendMailWithAttachments " + ex.Message + " " + ex.ToString() + " " + ex.InnerException.ToString()); } } catch (System.Exception e) { //if (IsLogging) LogHandler logHandler = new LogHandler(); logHandler.LogWarning("ERROR in SendMailWithAttachments: " + e.Message + " " + e.ToString() + "message : " + sFrom + " " + sTo + " " + sBody + " " + subject + " " + maAttachment.Length); } }
public void SendMail(string Token, CorreoNM correo = null) { oSmtp.SendCompleted += SendCompletedCallback; objCorreo = correo; oSmtp.SendAsync(oMail, Token); }
public bool EnviarMensajeCorreo(CitasBE oDatos, Parametros.EstadoCita oTipoCita, Parametros.PERSONA oPersona) { bool flEnvio = true; Int32 intResp = 0; mailSent = false; StringBuilder strHTML = new StringBuilder(); switch (oPersona) { case Parametros.PERSONA.CLIENTE: strHTML = CargarPlantilla_Cliente(oDatos, oTipoCita); break; case Parametros.PERSONA.ASESOR: strHTML = CargarPlantilla_Asesor(oDatos, oTipoCita); break; case Parametros.PERSONA.CALL_CENTER: strHTML = CargarPlantilla_CallCenter(oDatos, oTipoCita); break; } //Validando retorno del HTML if (strHTML.ToString().Equals("-1") || strHTML.ToString().Equals("-2")) { //-1 Error al cargar la Plantilla //-2 Error al rellenar Plantilla intResp = Int32.Parse(strHTML.ToString()); flEnvio = false; } else { System.Net.Mail.MailMessage oEmail = new System.Net.Mail.MailMessage(); System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(); try { string strAsunto = string.Empty; switch (oTipoCita) { case Parametros.EstadoCita.REGISTRADA: strAsunto = "SubjectCitaReserv"; break; case Parametros.EstadoCita.REPROGRAMADA: strAsunto = "SubjectCitaReprog"; break; case Parametros.EstadoCita.REASIGNADA: strAsunto = "SubjectCitaAsigna"; break; case Parametros.EstadoCita.ANULADA: strAsunto = "SubjectCitaAnula"; break; } oEmail.From = new System.Net.Mail.MailAddress(ConfigurationManager.AppSettings["MailAddress"], ConfigurationManager.AppSettings["DisplayName"]); switch (oPersona) { case Parametros.PERSONA.CLIENTE: if (!(oDatos.no_correo.Trim().ToString().Equals(""))) { oEmail.To.Add(oDatos.no_correo.Trim()); } if (!(oDatos.no_correo_trabajo.Trim().ToString().Equals(""))) { oEmail.To.Add(oDatos.no_correo_trabajo.Trim()); } if (!(oDatos.no_correo_alter.Trim().ToString().Equals(""))) { oEmail.To.Add(oDatos.no_correo_alter.Trim()); } break; case Parametros.PERSONA.ASESOR: oEmail.To.Add(oDatos.no_correo_asesor.Trim()); break; case Parametros.PERSONA.CALL_CENTER: oEmail.To.Add(oDatos.no_correo_callcenter.Trim()); break; } oEmail.Subject = ConfigurationManager.AppSettings[strAsunto]; oEmail.Body = strHTML.ToString(); oEmail.BodyEncoding = Encoding.GetEncoding("UTF-8"); oEmail.IsBodyHtml = true; oEmail.Priority = System.Net.Mail.MailPriority.High; //oEmail.Bcc.Add(ConfigurationManager.AppSettings["MailBcc"]); smtp.Host = ConfigurationManager.AppSettings["Host"]; smtp.Port = Convert.ToInt32(ConfigurationManager.AppSettings["Puerto"].ToString()); smtp.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["UsuarioMail"].ToString(), ConfigurationManager.AppSettings["ClaveMail"].ToString()); smtp.EnableSsl = true; smtp.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback); object userState = oEmail; try { //smtp.Send(oEmail); smtp.SendAsync(oEmail, userState); } catch (Exception ex) { no_error = string.Format("{0}|{1}", ex.Message, (ex.InnerException != null ? ex.InnerException.Message : string.Empty)); } finally { /*if (!mailSent) * smtp.SendAsyncCancel();*/ //oEmail.Dispose(); } } catch//(Exception ex) { flEnvio = false; } finally { oEmail = null; smtp = null; } } return(flEnvio); }
public async void SendMail(MailMessage message, IMailClient client, NetworkCredential network = null, bool async = true) { if (client == null) { await SendAsync(message); } else { message.From = new MailAddress(client.DisplayEmail, client.DisplayName); try { if (!string.IsNullOrEmpty(client.ReplyTo)) { message.ReplyToList.Add(client.ReplyTo); } if (!string.IsNullOrEmpty(client.CcList)) { message.CC.Add(client.CcList); } if (!string.IsNullOrEmpty(client.CcoList)) { message.Bcc.Add(client.CcoList); } } catch { } } try { //Smtp Mail server of Gmail is "smpt.gmail.com" and it uses port no. 587 //For different server like yahoo this details changes and you can //get it from respective server. System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient(client.Host, client.Port ?? 25); //Enable SSL mailClient.EnableSsl = client.EnableSsl ?? false; mailClient.UseDefaultCredentials = false; //todo: parametrizar isso ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return(true); }; if (network == null) { network = new NetworkCredential(client.UserName, client.Password.Decypher()); } mailClient.Credentials = network; mailClient.SendCompleted += (sender, e) => { if (e.Error != null) { System.Diagnostics.Trace.TraceError(e.Error.ToString()); } }; if (async) { mailClient.SendAsync(message, null); } else { mailClient.Send(message); } } catch (SmtpException smex) { throw new MosesApplicationException("Para o envio dos e-mails, é necessária uma conexão segura. Não foi possível autenticar a conta de email utilizada para os envios:" + smex.Message, smex); } catch (Exception ex) { throw new MosesApplicationException("Não foi possível enviar o email:" + ex.Message, ex); } }
public static void SendMail(string fromAddress, string fromName, List <string> emailAddresses, string emailSubject, string emailBody, List <string> attachments = null, MailPriority priority = MailPriority.Normal, List <string> ccAddresses = null, string bccAddresses = "", List <LinkedResource> linkedResources = null, Action onSuccess = null, Action <Exception> onError = null) { var ts = new Thread(() => { MailMessage msg = new MailMessage(); msg.From = new MailAddress(fromAddress, fromName); foreach (string email in emailAddresses) { msg.To.Add(email); } if (ccAddresses != null) { foreach (string email in ccAddresses) { msg.CC.Add(email); } } if (!string.IsNullOrEmpty(bccAddresses)) { msg.Bcc.Add(bccAddresses); } msg.Priority = priority; msg.Subject = emailSubject; msg.Body = emailBody; msg.IsBodyHtml = true; if (linkedResources != null) { AlternateView htmlView = AlternateView.CreateAlternateViewFromString(emailBody, null, "text/html"); linkedResources.ForEach(lr => htmlView.LinkedResources.Add(lr)); msg.AlternateViews.Add(htmlView); } if (attachments != null) { foreach (string attachment in attachments) { msg.Attachments.Add(new Attachment(attachment)); } } System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(); client.Host = Constants.EmailHost; //client.Port = MailSettings.Port; //client.EnableSsl = MailSettings.EnableSsl; // Credentials client.UseDefaultCredentials = false; client.Credentials = new NetworkCredential(Constants.EmailUsername, Constants.EmailPassword); client.DeliveryMethod = SmtpDeliveryMethod.Network; client.SendCompleted += (sender, e) => { if (e.Error == null) { SADFM.Base.NLogHelper.WriteEvent(NLog.LogLevel.Info, "Email successfully sent to {0}", string.Join(",", emailAddresses)); if (onSuccess != null) { onSuccess(); } return; } else { SADFM.Base.NLogHelper.WriteEvent(NLog.LogLevel.Info, "Email failed. [{0}]", string.Join(",", emailAddresses)); if (onError != null) { onError(e.Error); } } client.Dispose(); msg.Dispose(); }; // Use SendAsync to send the message asynchronously try { client.SendAsync(msg, null); } catch (Exception ex) { SADFM.Base.NLogHelper.WriteEvent(NLog.LogLevel.Info, "Email failed. [{0}]", string.Join(",", emailAddresses)); if (onError != null) { onError(ex); } } }); ts.Start(); }
public void SendAsync(MailMessage message, object userToken) { _smtpClient.SendAsync(message, userToken); }
/// <summary> /// /// </summary> /// <param name="to">收件人</param> /// <param name="cc">抄送人</param> /// <param name="bcc">密送人</param> /// <param name="message">邮件内容</param> /// <param name="isHtml">是否html内容</param> /// <returns></returns> public static bool SendMail(string[] to, string[] cc, string[] bcc, string subject, string message, bool isBodyHtml, bool useAsync, SendCompletedEventHandler sendCompleted) { if (string.IsNullOrEmpty(smtpServer)) { throw new Exception("邮件发送服务器未指定"); } if (string.IsNullOrEmpty(email)) { throw new Exception("发件人邮箱账号未指定"); } if (string.IsNullOrEmpty(password)) { throw new Exception("发件人邮箱密码未指定"); } if (to == null || to.Length == 0) { throw new Exception("收件人未指定"); } if (string.IsNullOrEmpty(subject)) { throw new Exception("邮件主题不能为空"); } if (string.IsNullOrEmpty(message)) { throw new Exception("邮件内容不能为空"); } System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage(); if (to != null) { foreach (var item in to) { msg.To.Add(item); } } if (cc != null) { foreach (var item in cc) { msg.CC.Add(item); } } if (bcc != null) { foreach (var item in bcc) { msg.Bcc.Add(item); } } msg.From = new System.Net.Mail.MailAddress(email, sender, Encoding.UTF8); msg.Subject = subject; msg.SubjectEncoding = Encoding.UTF8; msg.Body = message; msg.BodyEncoding = Encoding.UTF8; msg.IsBodyHtml = isBodyHtml; msg.Priority = System.Net.Mail.MailPriority.High; System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(smtpServer); smtp.Credentials = new System.Net.NetworkCredential(email, password); object userState = msg; try { if (useAsync) { smtp.SendAsync(msg, userState); if (sendCompleted != null) { smtp.SendCompleted += sendCompleted; } } else { smtp.Send(msg); } return(true); } catch (SmtpException ex) { throw ex; } }