public void sendPurchaseOrderToSupplier() { MailMessage purchaseOrderEmail = new MailMessage(); purchaseOrderEmail.To.Add(address); purchaseOrderEmail.From = new MailAddress("*****@*****.**"); purchaseOrderEmail.Subject = "Purchase Order From Williams Engraving and Specialty Supplies"; Attachment attachment = new Attachment(path, MediaTypeNames.Application.Octet); purchaseOrderEmail.Attachments.Add(attachment); using (SmtpClient smtp = new SmtpClient()) { try { smtp.Host = "smtp.gmail.com"; smtp.Port = 587; smtp.EnableSsl = true; smtp.DeliveryMethod = SmtpDeliveryMethod.Network; smtp.UseDefaultCredentials = false; smtp.Credentials = new NetworkCredential("*****@*****.**", "Pa$$word"); smtp.Send(purchaseOrderEmail); } catch (SmtpException ex) { smtp.Dispose(); } finally { purchaseOrderEmail.Dispose(); smtp.Dispose(); } } }
private void btn_SendReport_Click(object sender, EventArgs e) { String filepath = @"C:\bithubReports\Report.txt"; try { mail.MailMessage message; mail.SmtpClient smtp; message = new mail.MailMessage("*****@*****.**", "*****@*****.**", "OpScan Report", "Sample Body"); mail.Attachment att1 = new mail.Attachment(filepath); //mail.Attachment att2 = new mail.Attachment(@"C:\Users\fcs-bithub1\Documents\Hello.txt"); //mail.Attachment att3 = new mail.Attachment(@"C:\Users\fcs-bithub1\Documents\Hello.txt"); message.Attachments.Add(att1); //message.Attachments.Add(att2); //message.Attachments.Add(att3); //---------------------------------------------------------------- //SMTP INFORMATION smtp = new mail.SmtpClient("mta.hofstra.edu"); smtp.Send(message); smtp.Dispose(); this.Close(); MessageBox.Show("Report Has Been Sent!"); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private void sendBPMEmail() { var dateAndTime = DateTime.Now; var fromAddress = new MailAddress(this.fromTextBox.Text); var toAddress = new MailAddress(this.toTextBox.Text); var fromPassword = this.passwordTextBox.Text; var subject = dateAndTime.ToString("yyyy MMMM dd") + ": Heart Rate"; var body = "My heart rate was " + this.bpm + " on " + dateAndTime.ToString("yyyy MMMM dd") + " at " + dateAndTime.ToString("hh:mm tt"); var client = new SmtpClient { Host = "smtp.gmail.com", Port = 587, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, EnableSsl = true, Credentials = new NetworkCredential(fromAddress.Address, fromPassword) }; using (var message = new MailMessage(fromAddress, toAddress) { Subject = subject, Body = body }) { client.Send(message); } client.Dispose(); }
public static void Send(string toAddress,string subject,string body,string attachmentPath) { var smtp = new SmtpClient { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(ConfigurationManager.AppSettings["UserName"], ConfigurationManager.AppSettings["UserPassword"]) }; Attachment attachment; attachment = new Attachment(attachmentPath); var emailAddress = ConfigurationManager.AppSettings["TestEmailAddress"]; if(string.IsNullOrEmpty(emailAddress)) { emailAddress = toAddress; } var message = new MailMessage(ConfigurationManager.AppSettings["UserName"], emailAddress); message.Subject = subject; message.Body = body; if (!string.IsNullOrEmpty(attachmentPath)) message.Attachments.Add(attachment); smtp.Send(message); message.Dispose(); smtp.Dispose(); }
public async Task EmailSendAsync(MessageModel messageModel) { using (MailMessage mailMessage = new MailMessage()) { mailMessage.From = new MailAddress(_configuration.GetSection("EmailConfiguration").GetSection("FromEmail").Value.ToString(), _configuration.GetSection("EmailConfiguration").GetSection("FromName").Value.ToString(), Encoding.UTF8); mailMessage.Subject = messageModel.Subject; mailMessage.SubjectEncoding = Encoding.UTF8; mailMessage.Body = messageModel.Content; mailMessage.BodyEncoding = Encoding.UTF8; mailMessage.IsBodyHtml = true; mailMessage.BodyTransferEncoding = TransferEncoding.Base64; mailMessage.To.Add(new MailAddress(messageModel.To)); NetworkCredential networkCredential = new NetworkCredential(_configuration.GetSection("EmailConfiguration").GetSection("Username").Value.ToString(), _configuration.GetSection("EmailConfiguration").GetSection("Password").Value.ToString()); System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(); smtpClient.Host = _configuration.GetSection("EmailConfiguration").GetSection("SmtpServer").Value.ToString(); smtpClient.EnableSsl = Convert.ToBoolean(_configuration.GetSection("EmailConfiguration").GetSection("SSL").Value); smtpClient.UseDefaultCredentials = Convert.ToBoolean(_configuration.GetSection("EmailConfiguration").GetSection("UseDefaultCredentials").Value); smtpClient.Port = Convert.ToInt32(_configuration.GetSection("EmailConfiguration").GetSection("Port").Value); smtpClient.Credentials = networkCredential; smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; await smtpClient.SendMailAsync(mailMessage); smtpClient.Dispose(); } }
private void SmtpClient_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e) { // Get the MailMessage object MailMessage objMailMessage = (MailMessage)e.UserState; System.Net.Mail.SmtpClient objSmtpClient = (System.Net.Mail.SmtpClient)sender; if (e.Error != null) { BlazorBlogs.Data.Models.Logs objLog = new Data.Models.Logs(); objLog.LogDate = DateTime.Now; objLog.LogAction = $"{Constants.EmailError} - Error: {e.Error.GetBaseException().Message} - To: {objMailMessage.To} Subject: {objMailMessage.Subject}"; objLog.LogUserName = null; objLog.LogIpaddress = "127.0.0.1"; _context.Logs.Add(objLog); _context.SaveChanges(); } else { // Log the Email LogEmail(objMailMessage); objMailMessage.Dispose(); objSmtpClient.Dispose(); } }
public MailServiceOutBo execute() { MailServiceOutBo outBo = new MailServiceOutBo(); MyRepository rep = new MyRepository(); UserMst fromUser = rep.FindUserMstByUserId(BaseForm.UserInfo.userId); UserMst toUser = rep.FindMailingListUser(); string body = "承認者:" + fromUser.user_name + System.Environment.NewLine + this.inBo.messageBody; System.Net.Mail.MailMessage msg = new MailMessage(); System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient(); try { msg = new System.Net.Mail.MailMessage(fromUser.mail_address, toUser.mail_address, this.inBo.messageSubject, body); sc.Host = "localhost"; sc.Port = 25; sc.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; sc.Credentials = new System.Net.NetworkCredential(fromUser.mail_address, fromUser.password); sc.Send(msg); } catch (Exception ex) { StringBuilder sb = new StringBuilder(); sb.AppendLine(ex.Message); sb.AppendLine("TO・・・" + "ユーザー名:" + toUser.user_name + "、メールアドレス:" + toUser.mail_address); sb.AppendLine("FROM・・・" + "ユーザー名:" + fromUser.user_name + "、メールアドレス:" + fromUser.mail_address); outBo.errorMessage = sb.ToString(); } finally { msg.Dispose(); sc.Dispose(); } return(outBo); }
/// <summary> /// Sends the email. /// </summary> /// <param name="emailData">The email data.</param> public static void SendEmail(EmailMessageData emailData) { MailMessage mail = new MailMessage(); SmtpClient smtpServer = new SmtpClient(CurrentSmtpClient); smtpServer.Port = CurrentSmtpClientPort; mail.From = new MailAddress(emailData.FromEmail); foreach (string currentEmail in emailData.Emails) { mail.To.Add(currentEmail); } mail.Subject = emailData.Subject; mail.IsBodyHtml = true; mail.Body = emailData.EmailBody; AddAttachmentsToEmail(emailData, mail); smtpServer.Send(mail); DisposeAllAttachments(mail); mail.Dispose(); smtpServer.Dispose(); }
/// <summary> /// Method can be used to send an e-mail /// </summary> /// <param name="body">The contents of the message</param> /// <param name="address">the e-mail address of the sender</param> /// <param name="password">the password of the sender</param> /// <param name="server">sender's server</param> /// <param name="subject">The subject of the e-mail</param> /// <param name="attachment">Files to be attached</param> /// <param name="emailsSentTo">The emails of the recievers</param> public void SendMailSmtp(string body, string subject, Attachment attachment, string[] emailsSentTo) { var loginInfo = new NetworkCredential(_address, _password); var msg = new MailMessage { From = new MailAddress(_address) }; foreach (var s in emailsSentTo) { msg.To.Add(new MailAddress(s)); } msg.Subject = subject; msg.Body = body; msg.Attachments.Add(attachment); var smtpClient = new System.Net.Mail.SmtpClient(_server); smtpClient.EnableSsl = true; smtpClient.UseDefaultCredentials = true; smtpClient.Credentials = loginInfo; smtpClient.Send(msg); attachment.Dispose(); msg.Dispose(); smtpClient.Dispose(); }
public void Send() { try { var message = new MailMessage(Sender, Recipient, Subject, Body) { IsBodyHtml = true }; var smtp = new SmtpClient(_host, _port); if (_user.Length > 0 && _pass.Length > 0) { smtp.UseDefaultCredentials = false; smtp.Credentials = new NetworkCredential(_user, _pass); smtp.EnableSsl = _ssl; } smtp.Send(message); message.Dispose(); smtp.Dispose(); } catch (Exception ex) { throw new Exception("Send Email Error: " + ex.Message); } }
public async static TaskEventHandler SendEmailAsync(string email, string subject, string message) { try { var _email = "*****@*****.**"; var _epass = ConfigurationManager.AppSettings["EmailPassword"]; var _dispName = "Sean"; MailMessage myMessage = new MailMessage(); myMessage.To.Add(email); myMessage.From = new MailAddress(_email, _dispName); myMessage.Subject = subject; myMessage.Body = message; myMessage.IsBodyHtml = true; using (SmtpClient smtp = new SmtpClient()) { smtp.EnableSsl = true; smtp.Host = "smtp.live.com"; smtp.Port = 587; smtp.UseDefaultCredentials = false; smtp.Credentials = new NetworkCredential(_email, _epass); smtp.DeliveryMethod = SmtpDeliveryMethod.Network; smtp.SendCompleted += (s, e) => { smtp.Dispose(); }; await smtp.SendMailAsync(myMessage); } } catch(Exception ex) { throw ex; } }
public static void SendEmailAsync(string email, string subject, string body) { try { string _email = ConfigurationManager.AppSettings["mailAccount"]; string _epass = ConfigurationManager.AppSettings["mailPassword"]; string _dispName = "Oleg Kaliuga"; MailMessage Message = new MailMessage(); Message.To.Add(email); Message.From = new MailAddress(_email, _dispName); Message.IsBodyHtml = true; Message.Subject = subject; Message.Body = body; using (SmtpClient smtp = new SmtpClient()) { smtp.Host = "smtp.gmail.com"; smtp.Port = 587; smtp.UseDefaultCredentials = false; smtp.Credentials = new NetworkCredential(_email, _epass); smtp.DeliveryMethod = SmtpDeliveryMethod.Network; smtp.EnableSsl = true; smtp.SendCompleted += (s, e) => { smtp.Dispose(); }; smtp.Send(Message); } } catch (System.Exception ex) { throw ex; } }
/// <summary> /// Sends the specified message to an SMTP server for delivery. /// </summary> /// <param name="from">The address of the sender of the e-mail message.</param> /// <param name="to">The address of the recipient of the e-mail message.</param> /// <param name="subject">The subject line for this e-mail message</param> /// <param name="body">The message body.</param> /// <param name="host">The name or IP address of the host used for SMTP transactions.</param> public static void SendMail(string from, string to, string subject, string body, string host) { try { // Local variable declaration var mMessage = new MailMessage(); var smtpClient = new SmtpClient(); // Set value form MailMessage mMessage.From = new MailAddress(from); mMessage.To.Add(new MailAddress(to)); mMessage.Subject = subject; mMessage.IsBodyHtml = true; mMessage.Body = body; mMessage.Priority = MailPriority.Normal; // Set value form SmtpClient smtpClient.Host = host; smtpClient.UseDefaultCredentials = true; // Send smtpClient.Send(mMessage); // Dispose mMessage.Dispose(); smtpClient.Dispose(); } catch (Exception) { var message = MessageHelper.GetMessageFatal( "F_MSG_00002", Messages.F_MSG_00002_T, Messages.F_MSG_00002_H); throw new SysRuntimeException(message); } }
public static Boolean SendMail(String receiver, String message) { if (_mailer == null) { lock (_lock) { if (_mailer == null) { _mailer = MailLoadConfig.Load(); } } } //Prepare Message MailMessage mail = new MailMessage(); mail.From = new MailAddress(_mailer.smtpFromEmail, _fromName); mail.To.Add(receiver); mail.Subject = "Registration Confirmation Email"; mail.Body = message; //send the message SmtpClient smtp = new SmtpClient(_mailer.SmtpServer); smtp.Port = _mailer.SmtpPort; smtp.Credentials = new NetworkCredential(_mailer.SmtpUserName, _mailer.SmtpPassWord); smtp.EnableSsl = true; smtp.Send(mail); mail.Dispose(); smtp.Dispose(); return true; }
public void Enviar() { System.Net.Mail.MailMessage Mail = new System.Net.Mail.MailMessage(); System.Net.Mail.SmtpClient ObjectSmtp = new System.Net.Mail.SmtpClient(); Mail.From = new System.Net.Mail.MailAddress(Cuenta.no_email, Cuenta.no_usuario); /*Agregamos los correos a enviar To*/ if (!string.IsNullOrEmpty(Para)) { foreach (string item in Para.Split(';')) { if (item.Contains("@")) { Mail.To.Add(item); } } } /*Agregamos los correos a enviar CC*/ if (!string.IsNullOrEmpty(Copia)) { foreach (string item in Copia.Split(';')) { if (item.Contains("@")) { Mail.CC.Add(item); } } } /*Agregamos los archivos adjuntos*/ if (Adjunto != null) { foreach (string archivo in Adjunto) { Mail.Attachments.Add(new Attachment(archivo)); } } Mail.Subject = Asunto; Mail.Body = Mensaje; Mail.BodyEncoding = Encoding.GetEncoding("UTF-8"); Mail.IsBodyHtml = true; Mail.Priority = System.Net.Mail.MailPriority.High; ObjectSmtp.Host = Cuenta.no_host; ObjectSmtp.Port = Cuenta.nu_port; //if (Cuenta.nu_ssl == 0) // ObjectSmtp.EnableSsl = true; //else ObjectSmtp.EnableSsl = false; ObjectSmtp.Credentials = new System.Net.NetworkCredential(Cuenta.no_email, Cuenta.no_clave); ObjectSmtp.Send(Mail); Mail.Dispose(); ObjectSmtp.Dispose(); }
// copy from http://c-sharp-guide.com/?p=434 /// <summary> /// メールを送信します /// </summary> public void Send() { try { MailMessage msg = new MailMessage(); //送信者 msg.From = new MailAddress("送信者のアドレス"); //宛先(To) msg.To.Add(new MailAddress("宛先のアドレス1")); msg.To.Add(new MailAddress("宛先のアドレス2")); //宛先(Cc) msg.CC.Add(new MailAddress("CCのアドレス1")); msg.CC.Add(new MailAddress("CCのアドレス2")); //件名 msg.Subject = "件名"; //本文 msg.Body = "本文"; System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(); smtp.Host = "ホスト名"; //SMTPサーバーを指定 smtp.Port = 25; //(既定値は25) smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; smtp.Send(msg); msg.Dispose(); smtp.Dispose();//(.NET Framework 4.0以降) } catch (System.Exception e) { Console.Write(e.GetType().FullName + "の例外が発生しました。"); } }
public void SendMails() { List<string> receivers = GetList(); MailMessage mail = new MailMessage(); Encoding encoding = Encoding.GetEncoding(28591); SmtpClient client = new SmtpClient(); bool succes = false; try { mail.BodyEncoding = encoding; mail.Subject = message.Subject; mail.Body = message.Body; mail.IsBodyHtml = message.Body.Contains("<") && message.Body.Contains(">"); if (message.Sender != null) mail.From = new MailAddress(message.Sender); foreach (String recipient in receivers) { mail.Bcc.Add(recipient.Trim()); } client.Send(mail); client.Dispose(); succes = true; } catch (Exception e) { ExecuteNonQuery("Insert into MessageExceptions values( " + messageID + ", '" + e.Message + "', '" + e.StackTrace + "')"); } if (succes) RemoveFromQueue(receivers); }
public void Send(string subject, string text, string userMail) { SmtpClient smtpClient = null; MailMessage message = null; try { message = new MailMessage(new MailAddress(siteMail), new MailAddress(userMail)) { Subject = subject, Body = text }; smtpClient = new SmtpClient(host, Convert.ToInt32(ConfigurationManager.AppSettings["port"])) { Credentials = new NetworkCredential(siteMail, passWord) }; smtpClient.Send(message); } catch (SmtpException) { if (message != null) message.Dispose(); if (smtpClient != null) smtpClient.Dispose(); throw; } }
public static void enviarMail(Email datamail) { using (System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage()) { System.Net.Mail.MailAddress from = new System.Net.Mail.MailAddress(datamail.MailFrom, datamail.MailFromName); message.From = from; // Dirección de destino if (!string.IsNullOrEmpty(datamail.MailTo.Trim())) { message.To.Add(datamail.MailTo); } if (!string.IsNullOrEmpty(datamail.MailCC.Trim())) { message.CC.Add(datamail.MailCC); } if (!string.IsNullOrEmpty(datamail.MailBcc.Trim())) { message.Bcc.Add(datamail.MailBcc); } // Asunto message.Subject = datamail.Asunto; // Mensaje message.Body = datamail.Body; /* * if (!string.IsNullOrEmpty(datamail.Adjuntos)) * { * message.Attachments.Add(new System.Net.Mail.Attachment(rutafirma)); * } */ // Se envía el mensaje y se informa al usuario System.Net.Mail.SmtpClient smpt = new System.Net.Mail.SmtpClient(datamail.Smtp, datamail.PortSmtp); string mensaje = string.Empty; try { smpt.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; message.IsBodyHtml = true; smpt.EnableSsl = (datamail.Ssl) ? true : false; smpt.UseDefaultCredentials = false; //smpt.Credentials = new System.Net.NetworkCredential("*****@*****.**", usuario.PassMail); smpt.Timeout = 360000; smpt.Credentials = new System.Net.NetworkCredential(datamail.Usermail, datamail.Passmail); smpt.Send(message); } catch (Exception ex) { throw new Exception("Email no enviado: " + ex.Message); } finally { smpt.Dispose(); } } }
public void Dispose() { if (smtpClient != null) { smtpClient.Dispose(); } }
public static void SendEmail(TSPlayer player, string email, User user) { MailMessage mail = new MailMessage(AccountRecovery.Config.EmailFrom, email); SmtpClient client = new SmtpClient(); client.Timeout = 15000; client.Host = AccountRecovery.Config.HostSMTPServer; client.Port = AccountRecovery.Config.HostPort; client.DeliveryMethod = SmtpDeliveryMethod.Network; client.UseDefaultCredentials = false; client.Credentials = new System.Net.NetworkCredential(AccountRecovery.Config.ServerEmailAddress, AccountRecovery.Config.ServerEmailPassword); client.EnableSsl = true; //client.ServicePoint.MaxIdleTime = 1; mail.Subject = AccountRecovery.Config.EmailSubjectLine; mail.Body = AccountRecovery.Config.EmailBodyLine; mail.IsBodyHtml = AccountRecovery.Config.UseHTML; string passwordGenerated = GeneratePassword(AccountRecovery.Config.GeneratedPasswordLength); TShock.Users.SetUserPassword(user, passwordGenerated); TShock.Log.ConsoleInfo("{0} has requested a new password succesfully.", user.Name); mail.Body = string.Format(mail.Body.Replace("$NEW_PASSWORD", passwordGenerated)); mail.Body = string.Format(mail.Body.Replace("$USERNAME", user.Name)); client.Send(mail); client.Dispose(); player.SendSuccessMessage("A new password has been generated and sent to {0} for {1}.", email, user.Name); TShock.Log.ConsoleInfo("A new password has been generated and sent to {0} for {1}.", email, user.Name); }
private void send_email(string to) { try { mail.MailMessage message; mail.SmtpClient smtp; message = new mail.MailMessage("*****@*****.**", to, "OpScan Report", "Sample Body"); mail.Attachment att1 = new mail.Attachment(filepath); //mail.Attachment att2 = new mail.Attachment(@"C:\Users\fcs-bithub1\Documents\Hello.txt"); //mail.Attachment att3 = new mail.Attachment(@"C:\Users\fcs-bithub1\Documents\Hello.txt"); message.Attachments.Add(att1); //message.Attachments.Add(att2); //message.Attachments.Add(att3); //---------------------------------------------------------------- //SMTP INFORMATION smtp = new mail.SmtpClient("mta.hofstra.edu", 23); smtp.Send(message); smtp.Dispose(); Console.WriteLine("Report Has Been Sent!"); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
/// <summary> /// A method to send and email. It accepts the sender of the email, a list /// of recipients, the subject of the email, and the body of the email. /// </summary> /// <param name="sender"></param> /// <param name="recipients"></param> /// <param name="subject"></param> /// <param name="body"></param> public void sendEmail(string sender, List<string> recipients, string subject, StringBuilder body) { string username = "******"; string password = "******"; // Set the email parameters MailMessage mail = new MailMessage(); SmtpClient client = new SmtpClient("smtp.gmail.com", 587); client.EnableSsl = true; client.UseDefaultCredentials = false; System.Net.NetworkCredential credential = new System.Net.NetworkCredential(username, password); client.Credentials = credential; mail.From = new MailAddress(sender); foreach (string recipient in recipients) { mail.To.Add(recipient); } mail.Subject = subject; mail.Body = body.ToString(); // Send the email client.Send(mail); // Clean up client.Dispose(); mail.Dispose(); }
public static void SendEmail(EmailSenderData emailData) { MailMessage mail = new MailMessage(); SmtpClient smtpServer = new SmtpClient(emailData.SmtpClient); smtpServer.Port = 25; mail.From = new MailAddress(emailData.FromEmail); foreach (string currentEmail in emailData.Emails) { mail.To.Add(currentEmail); } mail.Subject = emailData.Subject; mail.IsBodyHtml = true; mail.Body = emailData.EmailBody; if (emailData.AttachmentPath != null) { foreach (string currentPath in emailData.AttachmentPath) { Attachment attachment = new Attachment(currentPath); mail.Attachments.Add(attachment); } smtpServer.Send(mail); DisposeAllAttachments(mail); } else { smtpServer.Send(mail); } mail.Dispose(); smtpServer.Dispose(); }
public void EnvoiMessage(string destinataire, string cc, string message, string objet) { try { //Objet Mail msg = new MailMessage(); // Expéditeur msg.From = new MailAddress(this.adresseExpediteur, this.nomExpediteur); // Destinataire(s) foreach (String dest in destinataire.Split(';')) { msg.To.Add(new MailAddress(dest, dest)); } // Destinataire(s) en copie if (cc != null && cc != "") { foreach (String destcc in cc.Split(';')) { msg.CC.Add(new MailAddress(destcc)); } } //Objet du mail msg.Subject = objet; //Corps du mail msg.Body = message; // Configuration SMTP client = new SmtpClient(SMTP, portSMTP); client.EnableSsl = false; client.Credentials = new NetworkCredential(SMTPUser, MDPSMTPUser); // Envoi du mail client.Send(msg); //Tue le mail msg.Dispose(); //Ferme la connexion au SMTP client.Dispose(); } catch (Exception ex) { //Tue le mail if (msg != null) { msg.Dispose(); } //Ferme la connexion au SMTP if (client != null) { client.Dispose(); } throw new Exception(ex.Message); } }
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 EmailWebService(string To, string From, string Subject, string Body) { SmtpClient smtp = new SmtpClient { Host = smtpServer }; MailMessage message = GetMailMessage(To, From, Subject, Body); smtp.Send(message); smtp.Dispose(); }
private void SendMessage(string body, string destAddr) { smtp = new SmtpClient("smtp.gmail.com", 587); smtp.EnableSsl = true; smtp.Credentials = new SMTPCreds(username, password); smtp.Send(username, destAddr, "BOT-REPLY", body); smtp.Dispose(); }
public string enviar_correo(string cabecera, string cuerpo, string receptor) { string htmlmensaje = ""; SmtpClient SMTPClientService = new System.Net.Mail.SmtpClient(); htmlmensaje = htmlmensaje = "<table width='650' align='enter' border=1 cellspacing=0 cellpadding=7 bordercolor='#C0D2E4'>"; htmlmensaje = htmlmensaje + " <tr>"; htmlmensaje = htmlmensaje + " <td align='right' style='background-color:#C0D2E4'><span style='font-family:Arial, Helvetica, sans-serif; color:#4C8AEF; font-size:25px; font-weight:bold; font-style:italic'>DILACO</span><span style='font-family:Arial, Helvetica, sans-serif; color:#445159; font-size:25px; font-weight:bold; font-style:italic'> informa</span><br />"; htmlmensaje = htmlmensaje + " <span style='font-family:Arial, Helvetica, sans-serif; color:#586974; font-size:13px; font-style:italic'>Sitio Web</span>"; htmlmensaje = htmlmensaje + " </td>"; htmlmensaje = htmlmensaje + " </tr>"; htmlmensaje = htmlmensaje + " <tr>"; htmlmensaje = htmlmensaje + " <td height=300 valign='top' style='background-color:#F8FAFC'><span style='font-family:'Trebuchet MS', Arial, Helvetica, sans-serif; color:#000; font-size:13px'>{BODY}</span></td>"; htmlmensaje = htmlmensaje + " </tr>"; htmlmensaje = htmlmensaje + " <tr>"; htmlmensaje = htmlmensaje + " <td height=20 valign='top' style='font-size:11px;font-family:'Trebuchet MS', Arial, Helvetica, sans-serif;border-top-color:#F8FAFC;border-top-width:0px;border-top-style:none'>Nota: Este email es enviado automaticamente. No responda a su remitente ya que no será leído.</td>"; htmlmensaje = htmlmensaje + " </tr>"; htmlmensaje = htmlmensaje + "</table>"; SMTPClientService.Host = "mail.dilaco.com"; SMTPClientService.Port = 25; SMTPClientService.EnableSsl = false; SMTPClientService.Credentials = new System.Net.NetworkCredential(correo_envia, "informatica#2021"); System.Net.Mail.MailMessage EmailMsgObj = new System.Net.Mail.MailMessage(); EmailMsgObj.IsBodyHtml = true; EmailMsgObj.To.Add(receptor); // EmailMsgObj.To.Add("*****@*****.**"); // EmailMsgObj.To.Add(receptor); EmailMsgObj.From = new System.Net.Mail.MailAddress(correo_envia); // EmailMsgObj.ReplyToList.Add("*****@*****.**"); EmailMsgObj.Subject = cabecera; //EmailMsgObj.Body = cuerpo.ToString(); EmailMsgObj.Body = htmlmensaje.Replace("{BODY}", cuerpo).ToString(); EmailMsgObj.IsBodyHtml = true; try { SMTPClientService.Send(EmailMsgObj); return("OK"); } catch (Exception ex) { return(ex.Message.ToString()); } finally { SMTPClientService.Dispose(); } }
public static bool Send(string to, string subject, string body, byte[] attach) { bool success = true; try { to = to.Replace(",", ";"); string[] addrs = to.Split(';'); var sendFrom = new MailAddress(MainForm.Conf.SMTPFromAddress.Trim()); var sendTo = new MailAddress(addrs[0].Trim()); var myMessage = new MailMessage(sendFrom, sendTo) { Subject = subject.Replace(Environment.NewLine, " ").Trim(), Body = body, IsBodyHtml = true }; if (addrs.Length > 1) { for (int i = 1; i < addrs.Length && i < 5; i++) { if (IsValidEmail(addrs[i].Trim())) myMessage.Bcc.Add(new MailAddress(addrs[i].Trim())); } } if (attach != null && attach.Length>0) { var attachFile = new Attachment(new MemoryStream(attach), "Screenshot.jpg"); myMessage.Attachments.Add(attachFile); } var emailClient = new SmtpClient(MainForm.Conf.SMTPServer, MainForm.Conf.SMTPPort) { UseDefaultCredentials = false, Credentials = new NetworkCredential(MainForm.Conf.SMTPUsername, MainForm.Conf.SMTPPassword), EnableSsl = MainForm.Conf.SMTPSSL }; emailClient.Send(myMessage); myMessage.Dispose(); myMessage = null; emailClient.Dispose(); emailClient = null; } catch (Exception ex) { success = false; MainForm.LogExceptionToFile(ex); } return success; }
public ActionResult Contact(Contact c) { if (c.Tutorial == false) { //cancel out error ModelState.Remove("TutorialID"); } if (ModelState.IsValid) { StringBuilder sb = new StringBuilder(); MailMessage msg = new MailMessage(); SmtpClient smtp = new SmtpClient(); MailAddress address = new MailAddress("*****@*****.**"); MailAddress from = new MailAddress(c.Email.ToString()); msg.Subject = "Contact Me"; msg.To.Add(address); msg.From = from; smtp.Host = "mail.ryanbutler.org"; smtp.Port = 25; msg.IsBodyHtml = false; sb.Append(Environment.NewLine); sb.Append("First name: " + c.FirstName); sb.Append(Environment.NewLine); sb.Append("Last name: " + c.LastName); sb.Append(Environment.NewLine); sb.Append("Email: " + c.Email); if (c.Tutorial == true) { sb.Append(Environment.NewLine); TutorialQuestionYes(sb, c); } else { sb.Append(Environment.NewLine); TutorialQuestionNo(sb); } sb.Append("Comments: " + c.Comment); msg.Body = sb.ToString(); try { smtp.Send(msg); smtp.Dispose(); msg.Dispose(); return View("Message"); } catch (Exception) { return View("Error"); } } var model = new Contact(); //send the bool tutorial radio button from the model to the view //in order to keep the div open model.Tutorial = c.Tutorial; PopulateDropDownList(c.TutorialID); return View(model); }
public bool SendEmailWithAttachment(string toAddress, string subject, string body, bool IsBodyHtml, string MsgFrom, string[] AttachmentFiles) { bool DisableMail = Convert.ToBoolean(ConfigurationManager.AppSettings["DisableMail"]); if (DisableMail) { return(true); } bool result = true; string senderID = Convert.ToString(ConfigurationManager.AppSettings["SmtpUserID"]); string senderPassword = Convert.ToString(ConfigurationManager.AppSettings["SmtpUserPassword"]); string Host = Convert.ToString(ConfigurationManager.AppSettings["SmtpHost"]); int Port = Convert.ToInt32(ConfigurationManager.AppSettings["SmtpPort"]); bool IsSslEnable = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]); MsgFrom = String.IsNullOrEmpty(MsgFrom) ? ConfigurationManager.AppSettings["MailFrom"] : MsgFrom; try { SmtpClient smtp = new System.Net.Mail.SmtpClient { Host = Host, Port = Port, EnableSsl = IsSslEnable, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new System.Net.NetworkCredential(senderID, senderPassword), Timeout = 30000, }; using (MailMessage message = new MailMessage(senderID, toAddress, subject, body)) { message.From = new MailAddress(senderID, MsgFrom); message.IsBodyHtml = IsBodyHtml; if (AttachmentFiles != null) { System.Net.Mail.Attachment attachment; foreach (var attachMent in AttachmentFiles) { attachment = new System.Net.Mail.Attachment(attachMent); message.Attachments.Add(attachment); attachment.Dispose(); } } smtp.Send(message); smtp.Dispose(); } } catch (Exception ex) { //Elmah.ErrorSignal.FromCurrentContext().Raise(ex); Logger.Error(ex.Message, ex); result = false; } return(result); }
/// <summary> /// metodo que envia el mail /// </summary> /// <returns></returns> public bool enviaMail() { bool exito = false; if (To.Trim().Equals("") || Message.Trim().Equals("") || Subject.Trim().Equals("")) { error = "El mail, el asunto y el mensaje son obligatorios"; return(false); } /* if (!ExpresionesRegulares.RegEX.isEmail(To)) * { * error = "El mail [" + To + "] no es un mail valido"; * return false; * }*/ //comienza------------------------------------------------------------------------- try { Email = new System.Net.Mail.MailMessage(From, To, Subject, Message); //si viene archivo a adjuntar if (Archivo != null) { //agregado de archivo foreach (string archivo in Archivo) { if (System.IO.File.Exists(@archivo)) { Email.Attachments.Add(new Attachment(@archivo)); } } } System.Net.Mail.SmtpClient smtpMail = new System.Net.Mail.SmtpClient(ConfigurationManager.AppSettings["serverSMTP"]); Email.IsBodyHtml = true; Email.From = new MailAddress(From); smtpMail.EnableSsl = false; smtpMail.UseDefaultCredentials = false; smtpMail.Host = ConfigurationManager.AppSettings["serverSMTP"]; smtpMail.Port = int.Parse(ConfigurationManager.AppSettings["portSMTP"]); smtpMail.Credentials = new System.Net.NetworkCredential(DE, PASS); smtpMail.Send(Email); smtpMail.Dispose(); mensaje = "Se envio el mail con exito"; exito = true; } catch (Exception ex) { error = "Ocurrio un error: " + ex.Message; exito = false; } return(exito); }
public void Send() { msg.Body = mail_body; SmtpClient SC = new SmtpClient("smtp.gmail.com",587); SC.Credentials = new NetworkCredential(smtp_user, smtp_pwd); SC.EnableSsl = true; SC.Send(this.msg); SC.Dispose(); }
/// <summary> /// metodo que envia el mail /// </summary> /// <returns></returns> public bool enviaMail() { //una validación básica if (To.Trim().Equals("") || Subject.Trim().Equals("")) { error = "El mail y el asunto"; return(false); } //aqui comenzamos el proceso //comienza------------------------------------------------------------------------- try { //creamos un objeto tipo MailMessage //este objeto recibe el sujeto o persona que envia el mail, //la direccion de procedencia, el asunto y el mensaje Email = new System.Net.Mail.MailMessage(From, To, Subject, Message); //si viene archivo a adjuntar //realizamos un recorrido por todos los adjuntos enviados en la lista //la lista se llena con direcciones fisicas, por ejemplo: c:/pato.txt if (Archivo != null) { Email.Attachments.Add(Archivo); } Email.IsBodyHtml = true; //definimos si el contenido sera html Email.From = new MailAddress(From); //definimos la direccion de procedencia //aqui creamos un objeto tipo SmtpClient el cual recibe el servidor que utilizaremos como smtp //en este caso me colgare de gmail System.Net.Mail.SmtpClient smtpMail = new System.Net.Mail.SmtpClient("smtp.gmail.com"); smtpMail.EnableSsl = true; //le definimos si es conexión ssl smtpMail.UseDefaultCredentials = false; //le decimos que no utilice la credencial por defecto smtpMail.Host = "smtp.gmail.com"; //agregamos el servidor smtp smtpMail.Port = 587; //le asignamos el puerto, en este caso gmail utiliza el 465 smtpMail.Credentials = new System.Net.NetworkCredential(DE, PASS); //agregamos nuestro usuario y pass de gmail //enviamos el mail smtpMail.Send(Email); //eliminamos el objeto smtpMail.Dispose(); //regresamos true return(true); } catch (Exception ex) { //si ocurre un error regresamos false y el error error = "Ocurrio un error: " + ex.Message; return(false); } }
public async Task sentEmail(string filename, string locationStr, int locationIndex) { try { System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(filename, System.Net.Mime.MediaTypeNames.Text.Html); var msg = new MailMessage(); List <string> emailList = _context.LocationEmail.Where(x => x.LocationIndex == locationIndex).Select(x => x.Email).ToList(); string emailListString = ""; foreach (string email in emailList) { msg.To.Add(new MailAddress(email)); } var credentialUserName = "******"; var sentFrom = "*****@gmail.com"; var pwd = "**********"; var smtp = new System.Net.Mail.SmtpClient("****.com", 587); var creds = new System.Net.NetworkCredential(credentialUserName, pwd); smtp.UseDefaultCredentials = false; smtp.Credentials = creds; smtp.EnableSsl = false; //var to = new MailAddress(emailListString); var from = new MailAddress(sentFrom, "SkyTech Mask Monitoring System"); //msg.To.Add(to); msg.From = from; msg.IsBodyHtml = true; msg.Subject = "Notification of people without mask"; msg.Body = "Date Time: " + DateTime.Now + "<br/>"; msg.Body = msg.Body + "Location: " + locationStr + "<br/><br/>"; msg.Body = msg.Body + "A person not wearing mask is discovered in the premises.<br/> This is a system generated email. Please do not reply."; if (attachment != null) { msg.Attachments.Add(attachment); } await smtp.SendMailAsync(msg); smtp.Dispose(); } catch (Exception ex) { Debug.WriteLine("Sent Email"); Debug.WriteLine(ex.InnerException); } finally { } }
/// <summary> /// Sends some messages to the SMTP server inbox, so we have something to query during this run. /// This is necessary cause currently mail is stored in a mock singleton, and not an actual db. /// </summary> private static void InitLocalTest() { for (int i = 0; i < 5; i++) { System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("localhost"); MailMessage msg = new MailMessage("*****@*****.**", "*****@*****.**", "otsikko", $"onpakakkaa {i}"); smtp.Send(msg); smtp.Dispose(); } client = new Pop3Client("yyy", "xxx", "localhost"); }
public static async Task<bool> SendAsync(ListaSpesaDto listaSpesa) { SmtpClient client = null; bool result = false; try { EmailDto message = await CreateBody(listaSpesa); // Credentials: var credentialUserName = ConfigurationManager.AppSettings["emailFrom"]; var sentFrom = ConfigurationManager.AppSettings["emailFrom"]; var pwd = ConfigurationManager.AppSettings["emailPassword"]; int port = Convert.ToInt32(ConfigurationManager.AppSettings["smtpPort"]); // Configure the client: client = new SmtpClient(ConfigurationManager.AppSettings["smtpClient"]) { Port = port, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["smtpEnableSSL"]), Credentials = new NetworkCredential(credentialUserName, pwd) }; AlternateView av = AlternateView.CreateAlternateViewFromString(message.Body, null, MediaTypeNames.Text.Html); // Create the message: MailMessage mail = new MailMessage() { IsBodyHtml = true, Priority = MailPriority.High, From = new MailAddress(ConfigurationManager.AppSettings["emailFrom"], "WishDays"), Subject = message.Subject }; mail.AlternateViews.Add(av); (await GetAddresses(message.Destination)).ToList().ForEach(m => { mail.To.Add(m); }); mail.From = new MailAddress(sentFrom); mail.Subject = message.Subject; // Send: await client.SendMailAsync(mail); result = true; } catch (Exception ex) { Console.Write(ex); } finally { client.Dispose(); } return result; }
public static void Send(string to, string title, string content) { MailMessage mailmessage = new MailMessage(From, to, title, content); //from email,to email,主题,邮件内容 mailmessage.IsBodyHtml = true; mailmessage.Priority = MailPriority.Normal; //邮件优先级 System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(Smtp, Port); //smtp地址以及端口号 smtpClient.Credentials = new NetworkCredential(Username, Password);//smtp用户名密码 smtpClient.Send(mailmessage); //发送邮件 smtpClient.Dispose(); mailmessage.Dispose(); }
public static void Send(string to, string title, string content) { MailMessage mailmessage = new MailMessage(From, to, title, content); //from email,to email,主题,邮件内容 mailmessage.IsBodyHtml = true; mailmessage.Priority = MailPriority.Normal; //邮件优先级 System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(Smtp, Port); //smtp地址以及端口号 smtpClient.Credentials = new NetworkCredential(Username, Password); //smtp用户名密码 smtpClient.Send(mailmessage); //发送邮件 smtpClient.Dispose(); mailmessage.Dispose(); }
public static bool SendMail(string body, string subject, string[] toaddress = null) { lock (LockMailForsend) { if (toaddress == null || toaddress.Length == 0) { return false; } MailMessage msg = new MailMessage(); foreach (var item in toaddress) { msg.To.Add(item); } //随机筛选一组用户 // int index = Rand.Next(0, SendMailAccount.Count); string username = "******";// SendMailAccount[index].Item1; string password = "******"; //SendMailAccount[index].Item2; //发件人信息 msg.From = new MailAddress(username, "慢慢买更新工具", Encoding.UTF8); msg.Subject = subject; //邮件标题 msg.SubjectEncoding = Encoding.UTF8; //标题编码 msg.Body = body; //邮件主体 msg.BodyEncoding = Encoding.UTF8; msg.IsBodyHtml = true; //是否HTML msg.Priority = MailPriority.High; SmtpClient client = new SmtpClient { Credentials = new System.Net.NetworkCredential(username, password), Port = 25, Host = "smtp.sina.com", EnableSsl = true }; try { client.Send(msg); return true; } catch(Exception ex) { LogServer.WriteLog(ex.Message,"EmailServer"); return false; } finally { msg.Dispose(); client.Dispose(); } } }
public static Boolean Sending(String email) { SmtpClient smtpclient = new SmtpClient("lynx.iss.nus.edu.sg"); MailMessage msg = new MailMessage("*****@*****.**", email); //msg.From = new MailAddress("*****@*****.**"); //msg.To = new MailMessage( msg.IsBodyHtml = true; msg.Subject = "Request for reset the password"; msg.Body = "You recently asked to reset your Facebook password. To complete your request, please follow this link: " + "http://localhost:1189/commonUI/Report.aspx" + "<p>"; smtpclient.Send(msg); smtpclient.Dispose(); return true; }
/// <summary> /// Envia um e-mail /// </summary> public void Enviar() { Verificacao(); var mensagem = new MailMessage { From = new MailAddress(_configuracaoEmail.Email), Subject = _configuracaoEmail.Assunto ?? string.Empty, //Se nenhum assunto foi informado, enviar vazio Body = _configuracaoEmail.Mensagem ?? string.Empty, //Se nenhuma mensagem foi informada, enviar vazio IsBodyHtml = _configuracaoEmail.MensagemEmHtml }; _destinatarios.ForEach(mensagem.To.Add); _anexos.ForEach(a => { mensagem.Attachments.Add(new Attachment(a, MediaTypeNames.Application.Octet)); }); var cliente = new SmtpClient(_configuracaoEmail.ServidorSmtp, _configuracaoEmail.Porta) { EnableSsl = _configuracaoEmail.Ssl, UseDefaultCredentials = false, DeliveryMethod = SmtpDeliveryMethod.Network, }; cliente.SendCompleted += (sender, args) => { if (args.Error != null) ErroAoEnviarEmail(args.Error); else OnDepoisDeEnviarEmail(); mensagem.Dispose(); cliente.Dispose(); }; var cred = new NetworkCredential(_configuracaoEmail.Email, _configuracaoEmail.Senha); cliente.Credentials = cred; cliente.Timeout = _configuracaoEmail.Timeout == 0 ? cliente.Timeout : _configuracaoEmail.Timeout; OnAntesDeEnviarEmail(); if (_configuracaoEmail.Assincrono) cliente.SendAsync(mensagem, null); else { cliente.Send(mensagem); OnDepoisDeEnviarEmail(); mensagem.Dispose(); cliente.Dispose(); } }
// GET api/values/5 public string Get(int id) { MailMessage mailMessage = new MailMessage(); MailAddress fromAddress = new MailAddress("*****@*****.**"); mailMessage.From = fromAddress; mailMessage.To.Add("*****@*****.**"); mailMessage.Body = "This is Testing Email Without Configured SMTP Server"; mailMessage.IsBodyHtml = true; mailMessage.Subject = " Testing Email"; System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("localhost"); smtp.Send(mailMessage); //Handles all messages in the protocol smtp.Dispose(); //sends a Quit message return("value"); }
public async Task SendAsync(IdentityMessage message) { SmtpClient client = null; try { // Credentials: var credentialUserName = ConfigurationManager.AppSettings["emailFrom"]; var sentFrom = ConfigurationManager.AppSettings["emailFrom"]; var pwd = ConfigurationManager.AppSettings["emailPassword"]; // Configure the client: client = new SmtpClient(ConfigurationManager.AppSettings["smtpClient"]) { Port = 25, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, EnableSsl = false, Credentials = new NetworkCredential(credentialUserName, pwd) }; // Creazione logo AlternateView av = AlternateView.CreateAlternateViewFromString(message.Body, null, MediaTypeNames.Text.Html); //av.LinkedResources.Add(await CreateEmbeddedImageAsync(HttpContext.Current.Server.MapPath("~/css/images/logo.png"), "logo")); // Create the message: MailMessage mail = new MailMessage(sentFrom, message.Destination) { IsBodyHtml = true, Priority = MailPriority.High, From = new MailAddress(ConfigurationManager.AppSettings["emailFrom"], "UPlayAgain"), Subject = message.Subject }; mail.AlternateViews.Add(av); mail.To.Add(new MailAddress(message.Destination)); mail.Subject = message.Subject; // Send: await client.SendMailAsync(mail); } catch(Exception ex) { _log.Error(ex); } finally { client.Dispose(); } }
public async Task SendAsync(IEnumerable<MailMessage> messages, Func<MailMessage, Task> continuationAction) { var tasks = new Collection<Task>(); foreach (var message in messages) { var message1 = message; var smtpClient = new SmtpClient(); Task task = smtpClient.SendMailAsync(message1) .ContinueWith(task1 => smtpClient.Dispose()); if (continuationAction != null) task = task.ContinueWith(t => continuationAction(message1)); tasks.Add(task); } await Task.WhenAll(tasks.ToArray()).ConfigureAwait(false); }
public static void EnviarEmail(string destinatario, string texto, string assunto) { SmtpClient client = new SmtpClient(); MailMessage message = new MailMessage() { Body = texto, Subject = assunto }; message.To.Add(new MailAddress(destinatario)); message.From = new MailAddress(ConfigurationManager.AppSettings["RemetenteEmailPadrao"]); message.IsBodyHtml = true; client.Send(message); client.Dispose(); }
public static void SendEmail(MailMessage objMail) { //var smtpClient = new SmtpClient { Host = "10.10.0.11" }; //smtpClient.Send(objMail); //smtpClient.Dispose(); //return; SmtpClient objSmtp = new SmtpClient(); System.Net.NetworkCredential basicAuthenticationInfo = new System.Net.NetworkCredential(smtpUsername, smtpPassword); objSmtp.Host = smtpServer; objSmtp.Port = int.Parse(smtpPort); objSmtp.Credentials = basicAuthenticationInfo; objSmtp.Send(objMail); objSmtp.Dispose(); }
public bool SendEmail(string toAddress, string subject, string body, bool IsBodyHtml, string MsgFrom) { bool DisableMail = Convert.ToBoolean(ConfigurationManager.AppSettings["DisableMail"]); if (DisableMail) { return(true); } bool result = true; string senderID = Convert.ToString(ConfigurationManager.AppSettings["SmtpUserID"]); string senderPassword = Convert.ToString(ConfigurationManager.AppSettings["SmtpUserPassword"]); string Host = Convert.ToString(ConfigurationManager.AppSettings["SmtpHost"]); int Port = Convert.ToInt32(ConfigurationManager.AppSettings["SmtpPort"]); bool IsSslEnable = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]); MsgFrom = String.IsNullOrEmpty(MsgFrom) ? ConfigurationManager.AppSettings["MailFrom"] : MsgFrom; try { SmtpClient smtp = new System.Net.Mail.SmtpClient { Host = Host, Port = Port, EnableSsl = IsSslEnable, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new System.Net.NetworkCredential(senderID, senderPassword), Timeout = 30000, }; using (MailMessage message = new MailMessage(senderID, toAddress, subject, body)) { message.From = new MailAddress(senderID, MsgFrom); message.IsBodyHtml = IsBodyHtml; //message.Attachments.Add(new Attachment(fileUploader.PostedFile.InputStream, fileName)); //message.Attachments.Add(new MailAttachment(Server.MapPath(strFileName));); smtp.Send(message); smtp.Dispose(); } } catch (Exception ex) { Logger.Error(ex.Message, ex); result = false; } return(result); }
public static bool SendEmail(string recipientEmail, string subject, byte[] pdf) { try { string SmtpServer = ConfigVars.NewInstance.Host;// "smtp.gmail.com"; //Smtp Port Number int SmtpPortNumber = ConfigVars.NewInstance.Port; System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(SmtpServer); MailMessage mMessage = new MailMessage(); string FromAddress = ConfigVars.NewInstance.From; string FromAdressTitle = ConfigVars.NewInstance.DisplayName; mMessage.From = new MailAddress(FromAddress); mMessage.To.Add(recipientEmail); mMessage.Subject = subject; mMessage.Body = "mail with attachment"; mMessage.IsBodyHtml = true; var contentType = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Application.Pdf); var myStream = new System.IO.MemoryStream(pdf); myStream.Seek(0, SeekOrigin.Begin); System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(myStream, "test.pdf"); mMessage.Attachments.Add(attachment); smtpClient.Port = SmtpPortNumber; smtpClient.Credentials = new System.Net.NetworkCredential(FromAddress, ConfigVars.NewInstance.Password); smtpClient.Send(mMessage); attachment.Dispose(); mMessage.Dispose(); smtpClient.Dispose(); return(true); } catch (Exception err) { Console.WriteLine("Error in sending mail: " + err.Message); return(false); } }
public bool toSendForAnnounce(string fromAccount, string pw, string receEmail, string SUBJECT, string mailbody, string fileName1, string fileName2, string fileName3) { try { //建立 SmtpClient 物件 並設定 Gmail的smtp主機及Port System.Net.Mail.SmtpClient MySmtp = new System.Net.Mail.SmtpClient("relay-hosting.secureserver.net"); //設定你的帳號密碼 MySmtp.Credentials = new System.Net.NetworkCredential(fromAccount, pw); //Gmial 的 smtp 必需要使用 SSL MySmtp.EnableSsl = false; MailMessage mms = new MailMessage(); mms.From = new MailAddress(fromAccount); mms.Bcc.Add(new MailAddress(receEmail)); mms.Subject = SUBJECT; mms.Body = mailbody; //附加檔案 if (fileName1.Trim() != "") { Attachment attachment = new Attachment(fileName1); mms.Attachments.Add(attachment); } if (fileName2.Trim() != "") { Attachment attachment = new Attachment(fileName2); mms.Attachments.Add(attachment); } if (fileName3.Trim() != "") { Attachment attachment = new Attachment(fileName3); mms.Attachments.Add(attachment); } //發送Email MySmtp.Send(mms); MySmtp.Dispose(); return(true); } catch (Exception e) { log.writeLogToFile("SendMail/toSend=>" + e.ToString()); return(false); } }
public static void sendMessage(string emailAddr, string passW) { /// ///<summary> ///Violently stolen from: https://github.com/cosullivan/SmtpServer ///By the way; NuGet is strange, but it works! ///</summary> // try { var fromAddress = new MailAddress("*****@*****.**", "From Admin"); var toAddress = new MailAddress(emailAddr, "To " + emailAddr.Substring(0, emailAddr.IndexOf("@"))); const string subject = "Welcome to windows chat Application!"; //formatted body for html string body = "<HTML>" + "<BODY>" + "<h1>Hello!</h1>" + "<p>You're all ready to login! You just need to make sure that you use your password to login :)</p>" + "<p><b style=\"color: #4286f4;\">Email: " + emailAddr + "</b></p>" + "<p><b style=\"color: #4286f4;\">Password: "******"</b></p>" + "</BODY></HTML>"; //it's pretty. System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(); smtp.EnableSsl = true; using (var message = new MailMessage(fromAddress, toAddress) { Subject = subject, Body = body }) { message.IsBodyHtml = true; smtp.Send(message); smtp.Dispose(); } } catch (Exception e) { System.Windows.Forms.MessageBox.Show(e.ToString()); } }
public static string SendMail(string mail, string subject, string body) { System.Net.Mail.SmtpClient smtp; string NotifyMessage = "Mail not Send"; MailAddress fromAddress = new MailAddress("*****@*****.**"); string fromPassword = "******"; MailAddress toAddress = new MailAddress(mail); smtp = new System.Net.Mail.SmtpClient { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(fromAddress.Address, fromPassword) }; try { using (MailMessage message = new MailMessage(fromAddress, toAddress) { Subject = subject, Body = body }) smtp.Send(message); NotifyMessage = "Mail has been send"; } catch (Exception e) { ExceptionLog.Log(e, "no ip : login model error email "); } finally { smtp.Dispose(); } return(NotifyMessage); }
public bool Send(string emailFrom, string emailTo, string subject, string body) { bool success = false; try { System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(config.Host, config.Port); client.EnableSsl = true; client.UseDefaultCredentials = false; client.DeliveryMethod = SmtpDeliveryMethod.Network; client.Credentials = new NetworkCredential(config.EmailFrom, config.FromPassword); MailMessage message = new MailMessage(emailFrom, emailTo); message.Subject = subject; message.Body = body; int retries = config.RetryCount; while (retries > 0 && success == false) { try { client.Send(message); success = true; } catch (Exception e) { success = false; retries--; } } message.Dispose(); client.Dispose(); } catch (Exception e) { } return(success); }
protected void Button1_Click(object sender, EventArgs e) { count(); Data(); str_allergens = str_allergens.TrimEnd(','); email2 = str_allergens.Split(','); for (int i = 0; i < rows; i++) { System.Net.Mail.SmtpClient MySmtp = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587); //設定你的帳號密碼 MySmtp.Credentials = new System.Net.NetworkCredential("*****@*****.**", "boy37201"); //Gmial 的 smtp 必需要使用 SSL MySmtp.EnableSsl = true; //發送Email MySmtp.Send("*****@*****.**", email2[i], "寵物廚房", TextBox3.Text); MySmtp.Dispose(); } Response.Redirect("/webs/manager/backmanagersearchcustomer.aspx"); }
private void SendEmail(string to) { System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage(); msg.Subject = "Email Subject"; msg.From = new System.Net.Mail.MailAddress("*****@*****.**"); msg.To.Add(to); msg.IsBodyHtml = true; msg.Body = "Read this from some file or db entry"; System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("email-smtp.us-east-1.amazonaws.com", 587); client.Credentials = new System.Net.NetworkCredential("AKIAJKQYX4CM6W4RO5HA", "AjJO/eIeBrn2SdJUT5ckqcot6VhMiS6pBawWxtKL8N8c"); client.EnableSsl = true; client.SendCompleted += (s, e) => { if (e.Error == null) { MGMProfileService svc = new MGMProfileService(DatabaseFactory.CreateMongoDatabase()); svc.UpdateEmailStatus(e.UserState.ToString(), true); } client.Dispose(); }; client.SendAsync(msg, to); }
public bool toSend(string fromAccount, string pw, string receEmail, string SUBJECT, string mailbody) { try { //建立 SmtpClient 物件 並設定 Gmail的smtp主機及Port System.Net.Mail.SmtpClient MySmtp = new System.Net.Mail.SmtpClient("relay-hosting.secureserver.net"); //SmtpClient MySmtp = new SmtpClient(); //設定你的帳號密碼 MySmtp.Credentials = new System.Net.NetworkCredential(fromAccount, pw); //Gmial 的 smtp 必需要使用 SSL MySmtp.EnableSsl = false; //發送Email log.writeLogToDB("", "SendMail/toSend", "start send"); MySmtp.Send(fromAccount, receEmail, SUBJECT, mailbody); MySmtp.Dispose(); log.writeLogToDB("", "SendMail/toSend", "end send"); return(true); } catch (Exception e) { log.writeLogToDB("", "SendMail/toSend", e.ToString()); return(false); } }
private void btnMail_Click(object sender, EventArgs e) { if (txtEmail.Text == "") { DialogResult result = MessageBox.Show("Email 不可為空!!\r\n繼續請按 Yes,離開請按 No。", "Error", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (result == DialogResult.No) { this.Close(); } } else { try { string Body = $"{lblAmonut.Text} : {txtRAmount.Text} \r\n " + $"{lblYear.Text} : {txtRYear.Text} \r\n " + $"{lblRate.Text} : {txtRRate.Text} \r\n " + $"{lblMonthPay.Text} : {txtRMonthPay.Text} \r\n" + $" {lblTotal.Text} : {txtRTotal.Text}"; System.Net.Mail.SmtpClient MySmtp = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587); MySmtp.Credentials = new System.Net.NetworkCredential("*****@*****.**", "wbiesolnfcrgmjfn"); MySmtp.EnableSsl = true; MySmtp.Send("測試主機端<*****@*****.**>", txtEmail.Text, "貸款報告書", Body); MySmtp.Dispose(); DialogResult result = MessageBox.Show("已發送報告\r\n繼續請按 Yes,離開請按 No。", "mail", MessageBoxButtons.YesNo, MessageBoxIcon.Information); if (result == DialogResult.No) { this.Close(); } } catch (Exception ex) { Form00.msgError(ex); } } }
/// <summary> /// This Method is used to Send eMail /// </summary> protected void SendMail() { MailMessage m = new MailMessage(); System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient(); try { string strHost = ConfigurationManager.AppSettings["Host"].ToString(); string strFromMailId = ConfigurationManager.AppSettings["EMailId"].ToString(); string strFromPassword = ConfigurationManager.AppSettings["Password"].ToString(); string strToMailId = "*****@*****.**"; //"*****@*****.**"; m.From = new MailAddress(strFromMailId); m.To.Add(new MailAddress(strToMailId)); m.Subject = "Payslip " + txtmonth.Text; m.IsBodyHtml = true; m.Body = "Please find the attachment of Payslip for " + txtmonth.Text; // Send With Attachment string FilePath = "~/Drawings/" + txtempcode.Text + "PaySlip.pdf"; FileStream fs = new FileStream(Server.MapPath(FilePath) + "", FileMode.Open, FileAccess.Read); Attachment a = new Attachment(fs, "Payslip " + txtmonth.Text + ".pdf"); m.Attachments.Add(a); sc.Host = strHost; sc.UseDefaultCredentials = false; sc.Credentials = new System.Net.NetworkCredential(strFromMailId, strFromPassword); sc.EnableSsl = false; sc.Send(m); sc.Dispose(); } catch (Exception ex) { Response.Write(ex.Message); } }
public static void sendMail(string email, string password) { try { var fromAddress = new MailAddress("*****@*****.**"); var fromPassword = "******"; var toAddress = new MailAddress(email); string subject = "Sistema UMA"; string body = "La contraseña para ingresar al sistema es: " + password; System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(fromAddress.Address, fromPassword) }; using (var message = new MailMessage(fromAddress, toAddress) { Subject = subject, Body = body, }) smtp.Send(message); smtp.Dispose(); } catch (Exception ex) { var x = ex; } }