public void SendEmail(string[] Tos, string Subject, System.Net.Mail.AlternateView Message, string[] FilePaths, string From = null) { Logger.Info(string.Format("SendEmail To: {0} Subject: {1} Message: {2}", string.Join(";", Tos), Subject, Message.ToString())); System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(); foreach (string To in Tos) { System.Net.Mail.MailAddress m = new System.Net.Mail.MailAddress(To); message.To.Add(m); } message.Subject = Subject; if (From == null) { message.From = new System.Net.Mail.MailAddress(SmtpFrom); } else { message.From = new System.Net.Mail.MailAddress(From); } message.AlternateViews.Add(Message); foreach (string FilePath in FilePaths) { if (!string.IsNullOrEmpty(FilePath)) { message.Attachments.Add(new System.Net.Mail.Attachment(FilePath)); } } System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(SmtpHost); smtp.Credentials = new System.Net.NetworkCredential(SmtpUser, SmtpPwd); smtp.Send(message); }
/// <summary> /// Create the Mail Message and hidrate with blob data /// </summary> /// <returns></returns> public System.Net.Mail.MailMessage ToMailMessage() { System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage(); msg.From = new System.Net.Mail.MailAddress(From); msg.Body = String.IsNullOrEmpty(BodyHtml) ? BodyText : BodyHtml; msg.Subject = Subject; foreach (string toItem in To) { msg.To.Add(toItem); } foreach (string bccItem in Bcc) { msg.Bcc.Add(bccItem); } foreach (string ccItem in Cc) { msg.CC.Add(ccItem); } msg.IsBodyHtml = !String.IsNullOrEmpty(BodyHtml); msg.Priority = System.Net.Mail.MailPriority.Normal; foreach (object item in Attachments) { System.Net.Mail.AlternateView view = new System.Net.Mail.AlternateView( new MemoryStream((item as MimeEntry).Data), (item as MimeEntry).ContentType); msg.AlternateViews.Add(view); } return(msg); }
public static bool SendEmail(SMTPemail smtp, string Email, string Password, string UserName) { string fromStr = smtp.EmailUsernames; string fromName = smtp.FromName; System.Net.Mail.MailAddress fromAddr = new System.Net.Mail.MailAddress(fromStr, fromName, System.Text.Encoding.UTF8); System.Net.Mail.MailAddress toAddr = new System.Net.Mail.MailAddress(Email, "user", System.Text.Encoding.UTF8); System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(fromAddr, toAddr); string body = "<html><body><p>Hi ,<br/><br/>"; body += "Your Password is:<strong>" + Password + "</strong><br/>"; body += "Your UserName is:<strong>" + UserName + "</strong><br/>"; body += "Please do not share these details with anybody.<br/>"; body += "Regards<br/>"; body += "Password Manager<br/>"; body += "<br/></p></body></html>"; System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(body, null, "text/html"); System.Net.Mail.AlternateView plainView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(System.Text.RegularExpressions.Regex.Replace(body, @"<(.|\n)*?>", string.Empty), null, "text/plain"); System.Net.Mail.SmtpClient mailclient = new System.Net.Mail.SmtpClient(smtp.SMTPservers, int.Parse(smtp.EmailPorts)); message.IsBodyHtml = true; message.Subject = "Password " + fromName; message.SubjectEncoding = System.Text.Encoding.UTF8; message.Headers.Add("Return-Path", fromName + "<" + fromStr + ">"); message.Headers.Add("Reply-To", fromName + "<" + fromStr + ">"); message.Headers.Add("From", fromName + "<" + fromStr + ">\r\n"); message.Headers.Add("Organization", "Get Balance"); message.Headers.Add("MIME-Version", "1.0\r\n"); message.Headers.Add("Content-type", "text/html; charset=ISO-8859-1\r\n"); DateTime now = DateTime.Now; message.Headers.Add("Message-Id", String.Concat("<", now.ToString("yyMMdd"), ".", now.ToString("HHmmss"), "@Tetramind.com")); message.Priority = System.Net.Mail.MailPriority.High; message.ReplyTo = fromAddr; message.From = fromAddr; message.Sender = fromAddr; mailclient.UseDefaultCredentials = false; message.BodyEncoding = System.Text.Encoding.UTF8; message.Body = body; message.DeliveryNotificationOptions = System.Net.Mail.DeliveryNotificationOptions.OnFailure; mailclient.EnableSsl = true; mailclient.Credentials = new System.Net.NetworkCredential(fromStr, smtp.EmailPasswords); mailclient.Send(message); return(true); }
} // End Constructor // https://stackoverflow.com/questions/18358534/send-inline-image-in-email private static System.Net.Mail.AlternateView GetAlternativeView(string htmlBody, System.Collections.Generic.List <Resource> embeddedImages) { foreach (Resource thisResource in embeddedImages) { htmlBody = htmlBody.Replace(thisResource.FileName, "cid:" + thisResource.UID); } // Next thisResource System.Net.Mail.AlternateView alternateView = System.Net.Mail.AlternateView.CreateAlternateViewFromString( htmlBody , null , System.Net.Mime.MediaTypeNames.Text.Html ); foreach (Resource thisResource in embeddedImages) { System.Net.Mail.LinkedResource res = new System.Net.Mail.LinkedResource( thisResource.Stream , thisResource.ContentType ); res.ContentId = thisResource.UID; alternateView.LinkedResources.Add(res); } // Next thisResource return(alternateView); } // End Function GetAlternativeView
private Task configSendGridasync(IdentityMessage message) { System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage(); System.Net.Mail.SmtpClient SmtpServer = new System.Net.Mail.SmtpClient("172.16.0.115", 25); mail.To.Add(message.Destination); mail.From = new System.Net.Mail.MailAddress("*****@*****.**"); mail.Subject = string.Format("Please Confirm Your Email {0:dddd, MMMM d, yyyy}", DateTime.Now); mail.IsBodyHtml = true; System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString ( message.Body, System.Text.Encoding.UTF8, "text/html" ); try { mail.AlternateViews.Add(htmlView); SmtpServer.Send(mail); } catch (Exception) { throw; } return(Task.FromResult(0)); }
private void EmailResults(IdentityMessage message) { System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage(); System.Net.Mail.SmtpClient SmtpServer = new System.Net.Mail.SmtpClient("172.16.0.115", 25); mail.To.Add(message.Destination); mail.From = new System.Net.Mail.MailAddress("*****@*****.**"); mail.IsBodyHtml = true; System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString ( message.Body, System.Text.Encoding.UTF8, "text/html" ); try { mail.AlternateViews.Add(htmlView); SmtpServer.Send(mail); } catch (Exception) { throw; } }
public void Add(System.Net.Mail.AlternateView alternate) { base.Add(new MailMessageAlternateView { Content = alternate.ContentStream.ToByteArray(), ContentType = alternate.ContentType.MediaType }); }
/// <summary> /// Get Master Body HTML. /// </summary> /// <param name="body">Body Text.</param> /// <param name="subject">Mail Subject.</param> /// <param name="emailType">Email Type.</param> /// <param name="languageId">User Language.</param> /// <returns>Alternate View.</returns> private static System.Net.Mail.AlternateView GetMasterBody(string body, string subject, EmailType emailType, int languageId, string sender, string mailLogo, string LoginUrl) { string logoPath = string.Empty; string mailLogoPath = string.Empty; if (emailType == EmailType.Default) { logoPath = ProjectConfiguration.SiteUrlBase + "/images/logo.png"; mailLogoPath = ProjectConfiguration.SiteUrlBase + "/images/" + mailLogo; string masterEmailTemplate = string.Empty; if (subject == Constants.BORROWBOOK_REQUEST_FOR_ADMIN || subject == Constants.ROOM_BOOKING_REQUEST_FOR_ADMIN) { masterEmailTemplate = Email.GetEmailTemplate(SystemEnumList.EmailTemplateFileName.MasterEmailTemplateForAdmin.ToString(), languageId); masterEmailTemplate = masterEmailTemplate.Replace("[@SUBJECT]", subject); } else { masterEmailTemplate = Email.GetEmailTemplate(SystemEnumList.EmailTemplateFileName.MasterEmailTemplate.ToString(), languageId); masterEmailTemplate = masterEmailTemplate.Replace("[@SUBJECT]", subject.ToUpper()); } body = masterEmailTemplate.Replace("[@BODYCONTENT]", body); body = body.Replace("[@Sender]", sender); if (LoginUrl == null) { LoginUrl = ProjectConfiguration.FrontEndSiteUrl; } body = body.Replace("[@LoginUrl]", LoginUrl); if (subject == Constants.FORGOT_PASSWORD) { body = body.Replace("[@LoginText]", "Reset"); } else { body = body.Replace("[@LoginText]", "Login"); } } else { logoPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"images") + "/logo.png"; mailLogoPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"images") + "/" + mailLogo; } System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(body, null, "text/html"); if (!string.IsNullOrEmpty(logoPath)) { htmlView.LinkedResources.Add(GetImageResource("LogoImage", logoPath)); } if (!string.IsNullOrEmpty(mailLogo)) { htmlView.LinkedResources.Add(GetImageResource("MailHeaderIcon", mailLogoPath)); } return(htmlView); }
} // End Sub SendAttachment // https://stackoverflow.com/questions/18358534/send-inline-image-in-email private static System.Net.Mail.AlternateView GetAlternativeView(string htmlBody, string filePath) { System.Net.Mail.LinkedResource res = new System.Net.Mail.LinkedResource(filePath, "image/png"); res.ContentId = System.Guid.NewGuid().ToString(); htmlBody = htmlBody.Replace("{@COR_LOGO}", "cid:" + res.ContentId); System.Net.Mail.AlternateView alternateView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(htmlBody, null, System.Net.Mime.MediaTypeNames.Text.Html); alternateView.LinkedResources.Add(res); return(alternateView); } // End Function GetAlternativeView
private bool SendEmail() { try { //create the mail message using (System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage()) { //set the addresses mail.From = new System.Net.Mail.MailAddress(UserSettings.MAIL_USERNAME); mail.To.Add(_emailAddress); //set the content mail.Subject = "Closet Drawing"; mail.Attachments.Add(new System.Net.Mail.Attachment(_closetDrawingPath)); //first we create the Plain Text part System.Net.Mail.AlternateView plainView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(String.Format("{0}Width (feet) : {1}{0}Depth (feet) : {2}{0}Height (feet) : {3}{0}Ply Thickness (inches) : {4}{0}Door Height as % of total height: {5}{0}Number of drawers : {6}{0}Is Split drawers ? : {7}{0}" , Environment.NewLine, _width, _depth, _height, _plyThickness, _doorHeightPercentage, _iNumOfDrawers, _isSplitDrawers), null, "text/plain"); //then we create the Html part //to embed images, we need to use the prefix 'cid' in the img src value //the cid value will map to the Content-Id of a Linked resource. //thus <img src='cid:companylogo'> will map to a LinkedResource with a ContentId of 'companylogo' System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString("<html><body><h3>Here is a preview of the closet. AutoCAD drawing file is attached.</h3><br/><img src='cid:closetimg'/></body></html>", null, "text/html"); if (!String.IsNullOrEmpty(_imagePath)) { //create the LinkedResource (embedded image) System.Net.Mail.LinkedResource closetLR = new System.Net.Mail.LinkedResource(_imagePath); closetLR.ContentId = "closetimg"; htmlView.LinkedResources.Add(closetLR); } //add the views mail.AlternateViews.Add(plainView); mail.AlternateViews.Add(htmlView); //send the message using (System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587)) { smtpClient.Credentials = new System.Net.NetworkCredential(UserSettings.MAIL_USERNAME, UserSettings.MAIL_PASSWORD); smtpClient.EnableSsl = true; smtpClient.Send(mail); } } } catch (Exception ex) { return(false); } return(true); }
private static System.Net.Mail.AlternateView GetMasterBodyForWindowService(string body, string subject, string path) { string masterEmailTemplate = Email.GetEmailTemplateForWindowService(SystemEnum.EmailTemplateFileName.MasterEmailTemplate.ToString(), path); body = masterEmailTemplate.Replace("[@MainContent]", body); body = body.Replace("[@Subject]", subject); System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(body, null, "text/html"); string logo = path + "\\Content\\images\\logo.png"; System.Net.Mail.LinkedResource logoResource = new System.Net.Mail.LinkedResource(logo, "image/gif"); logoResource.ContentId = "LogoImage"; logoResource.TransferEncoding = System.Net.Mime.TransferEncoding.Base64; htmlView.LinkedResources.Add(logoResource); return(htmlView); }
static void Main(string[] args) { string SMTPUser = "******"; string SMTPPassword = "******"; int SmtpPort = 587; string SmtpServer = "smtp.yandex.com"; System.Net.Mail.MailAddress sender = new System.Net.Mail.MailAddress("*****@*****.**", "", System.Text.Encoding.UTF8); System.Net.Mail.MailAddress recipient = new System.Net.Mail.MailAddress("*****@*****.**", "", System.Text.Encoding.UTF8); System.Net.Mail.MailMessage email = new System.Net.Mail.MailMessage(sender, recipient); email.BodyEncoding = System.Text.Encoding.UTF8; email.SubjectEncoding = System.Text.Encoding.UTF8; System.Net.Mail.AlternateView plainView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(System.Text.RegularExpressions.Regex.Replace("My plan body", @"<(.|\n)*?>", string.Empty), null, MediaTypeNames.Text.Plain); System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString("My HTML body", null, MediaTypeNames.Text.Html); email.AlternateViews.Clear(); email.AlternateViews.Add(plainView); email.AlternateViews.Add(htmlView); email.Subject = $"Azure {DateTime.Now}"; System.Net.Mail.SmtpClient SMTP = new System.Net.Mail.SmtpClient(); SMTP.UseDefaultCredentials = false; SMTP.Host = SmtpServer; SMTP.Port = SmtpPort; SMTP.Credentials = new System.Net.NetworkCredential(SMTPUser, SMTPPassword); SMTP.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; SMTP.EnableSsl = true; SMTP.Send(email); }
/// <summary> /// Get Master Body HTML /// </summary> /// <param name="body">Body Text</param> /// <param name="subject">Mail Subject</param> /// <param name="emailType">Email Type</param> /// <returns>Alternate View</returns> private static System.Net.Mail.AlternateView GetMasterBody(string body, string subject, EmailType emailType) { if (emailType == EmailType.Default) { string masterEmailTemplate = Email.GetEmailTemplate(SystemEnum.EmailTemplateFileName.MasterEmailTemplate.ToString()); body = masterEmailTemplate.Replace("[@MainContent]", body); body = body.Replace("[@Subject]", subject); System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(body, null, "text/html"); string logo = ProjectConfiguration.ApplicationRootPath + "\\Content\\images\\logo.png"; System.Net.Mail.LinkedResource logoResource = new System.Net.Mail.LinkedResource(logo, "image/gif"); logoResource.ContentId = "LogoImage"; logoResource.TransferEncoding = System.Net.Mime.TransferEncoding.Base64; htmlView.LinkedResources.Add(logoResource); return(htmlView); } else { return(System.Net.Mail.AlternateView.CreateAlternateViewFromString(body, null, "text/html")); } }
public void SendNotification(string FromEmail, string ToEmail, string Subject, string BodyText, string BodyHTML, int ForumID = 0, int TopicId = 0, int ReplyId = 0) { try { Subject = Subject.Replace("[", "["); Subject = Subject.Replace("]", "]"); if (SmtpServer == string.Empty && SmtpUserName == string.Empty && SmtpPassword == string.Empty && SmtpAuthentication == string.Empty && SmtpSSL == string.Empty) { var objHost = new Entities.Host.HostSettingsController(); IDataReader drHost = objHost.GetHostSettings(); while (drHost.Read()) { if (Convert.ToString(drHost["SettingName"]) == "SMTPServer") { SmtpServer = Convert.ToString(drHost["SettingValue"]); } if (Convert.ToString(drHost["SettingName"]) == "SMTPUsername") { SmtpUserName = Convert.ToString(drHost["SettingValue"]); } if (Convert.ToString(drHost["SettingName"]) == "SMTPPassword") { SmtpPassword = Convert.ToString(drHost["SettingValue"]); } if (Convert.ToString(drHost["SettingName"]) == "SMTPEnableSSL") { SmtpSSL = Convert.ToString(drHost["SettingName"]); } if (Convert.ToString(drHost["SettingName"]) == "SMTPAuthentication") { SmtpAuthentication = Convert.ToString(drHost["SettingValue"]); } } drHost.Close(); drHost.Dispose(); } var Email = new System.Net.Mail.MailMessage(); try { } catch (Exception ex) { } Email.From = new System.Net.Mail.MailAddress(FromEmail); Email.To.Add(new System.Net.Mail.MailAddress(ToEmail)); string sGuid = ""; try { //sGuid = DataProvider.Instance.ActiveForums_MC_GetPostGUID(TopicId).ToString } catch (Exception ex) { } if (sGuid == "00000000-0000-0000-0000-000000000000" || sGuid == "") { sGuid = ""; } else { sGuid = " (" + sGuid + ")"; } if (TopicId == 0) { Email.Subject = Subject; } else { Email.Subject = Subject + sGuid; } if (BodyHTML == string.Empty) { Email.Body = BodyText; Email.IsBodyHtml = false; } else if (BodyText == string.Empty) { Email.Body = BodyHTML; Email.IsBodyHtml = true; } else { System.Net.Mail.AlternateView plainView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(BodyText, null, "text/plain"); System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(BodyHTML, null, "text/html"); Email.AlternateViews.Add(plainView); Email.AlternateViews.Add(htmlView); } var client = new System.Net.Mail.SmtpClient(); if (SmtpServer != "") { int portPos = SmtpServer.IndexOf(":"); if (portPos > -1) { client.Port = Convert.ToInt32(SmtpServer.Substring(portPos + 1, SmtpServer.Length - portPos - 1)); SmtpServer = SmtpServer.Substring(0, portPos); } client.Host = SmtpServer; // with authentication //If SmtpUserName <> "" And SmtpPassword <> "" Then // client.UseDefaultCredentials = False // client.Credentials = New Net.NetworkCredential(SmtpUserName, SmtpPassword) //End If } switch (SmtpAuthentication) { case "": case "0": // anonymous break; case "1": // basic if (SmtpUserName != "" & SmtpPassword != "") { client.UseDefaultCredentials = false; client.Credentials = new System.Net.NetworkCredential(SmtpUserName, SmtpPassword); } break; case "2": // NTLM client.UseDefaultCredentials = true; break; } if (SmtpSSL == "Y" || SmtpServer.Contains("gmail")) { client.EnableSsl = true; } //Logger.Log("Email.vb line 256") try { client.Send(Email); } catch (Exception ex) { //Logger.Log("Email.vb line 260" & ex.ToString) Services.Exceptions.Exceptions.LogException(ex); } } catch (Exception ex) { //Logger.Log("Email.vb line 264" & ex.ToString) Services.Exceptions.Exceptions.LogException(ex); } }
private static string SendMail(bool SendAsync, string DefaultConnection, string MailFrom, string MailTo, string MailToDisplayName, string Cc, string Bcc, string ReplyTo, string Header, System.Net.Mail.MailPriority Priority, string Subject, Encoding BodyEncoding, string Body, string[] Attachment, string SMTPServer, string SMTPAuthentication, string SMTPUsername, string SMTPPassword, bool SMTPEnableSSL) { string strSendMail = ""; GeneralSettings GeneralSettings = new GeneralSettings(DefaultConnection); // SMTP server configuration if (SMTPServer == "") { SMTPServer = GeneralSettings.SMTPServer; if (SMTPServer.Trim().Length == 0) { return("Error: Cannot send email - SMTPServer not set"); } } if (SMTPAuthentication == "") { SMTPAuthentication = GeneralSettings.SMTPAuthendication; } if (SMTPUsername == "") { SMTPUsername = GeneralSettings.SMTPUserName; } if (SMTPPassword == "") { SMTPPassword = GeneralSettings.SMTPPassword; } MailTo = MailTo.Replace(";", ","); Cc = Cc.Replace(";", ","); Bcc = Bcc.Replace(";", ","); System.Net.Mail.MailMessage objMail = null; try { System.Net.Mail.MailAddress SenderMailAddress = new System.Net.Mail.MailAddress(MailFrom, MailFrom); System.Net.Mail.MailAddress RecipientMailAddress = new System.Net.Mail.MailAddress(MailTo, MailToDisplayName); objMail = new System.Net.Mail.MailMessage(SenderMailAddress, RecipientMailAddress); if (Cc != "") { objMail.CC.Add(Cc); } if (Bcc != "") { objMail.Bcc.Add(Bcc); } if (ReplyTo != string.Empty) { objMail.ReplyToList.Add(new System.Net.Mail.MailAddress(ReplyTo)); } objMail.Priority = (System.Net.Mail.MailPriority)Priority; objMail.IsBodyHtml = IsHTMLMail(Body); objMail.Headers.Add("In-Reply-To", $"ADefHelpDesk-{Header}"); foreach (string myAtt in Attachment) { if (myAtt != "") { objMail.Attachments.Add(new System.Net.Mail.Attachment(myAtt)); } } // message objMail.SubjectEncoding = BodyEncoding; objMail.Subject = Subject.Trim(); objMail.BodyEncoding = BodyEncoding; System.Net.Mail.AlternateView PlainView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(Utility.ConvertToText(Body), null, "text/plain"); objMail.AlternateViews.Add(PlainView); //if body contains html, add html part if (IsHTMLMail(Body)) { System.Net.Mail.AlternateView HTMLView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(Body, null, "text/html"); objMail.AlternateViews.Add(HTMLView); } } catch (Exception objException) { // Problem creating Mail Object strSendMail = MailTo + ": " + objException.Message; // Log Error to the System Log Log.InsertSystemLog(DefaultConnection, Constants.EmailError, "", strSendMail); } if (objMail != null) { // external SMTP server alternate port int?SmtpPort = null; int portPos = SMTPServer.IndexOf(":"); if (portPos > -1) { SmtpPort = Int32.Parse(SMTPServer.Substring(portPos + 1, SMTPServer.Length - portPos - 1)); SMTPServer = SMTPServer.Substring(0, portPos); } System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(); if (SMTPServer != "") { smtpClient.Host = SMTPServer; smtpClient.Port = (SmtpPort == null) ? (int)25 : (Convert.ToInt32(SmtpPort)); switch (SMTPAuthentication) { case "": case "0": // anonymous break; case "1": // basic if (SMTPUsername != "" & SMTPPassword != "") { smtpClient.UseDefaultCredentials = false; smtpClient.Credentials = new System.Net.NetworkCredential(SMTPUsername, SMTPPassword); } break; case "2": // NTLM smtpClient.UseDefaultCredentials = true; break; } } smtpClient.EnableSsl = SMTPEnableSSL; try { if (SendAsync) // Send Email using SendAsync { // Set the method that is called back when the send operation ends. smtpClient.SendCompleted += SmtpClient_SendCompleted; // Send the email DTOMailMessage objDTOMailMessage = new DTOMailMessage(); objDTOMailMessage.DefaultConnection = DefaultConnection; objDTOMailMessage.MailMessage = objMail; smtpClient.SendAsync(objMail, objDTOMailMessage); strSendMail = ""; } else // Send email and wait for response { smtpClient.Send(objMail); strSendMail = ""; // Log the Email LogEmail(DefaultConnection, objMail); objMail.Dispose(); smtpClient.Dispose(); } } catch (Exception objException) { // mail configuration problem if (!(objException.InnerException == null)) { strSendMail = string.Concat(objException.Message, Environment.NewLine, objException.InnerException.Message); } else { strSendMail = objException.Message; } // Log Error to the System Log Log.InsertSystemLog(DefaultConnection, Constants.EmailError, "", strSendMail); } } return(strSendMail); }
/// <summary> /// Create the Mail Message and hidrate with blob data /// </summary> /// <returns></returns> public System.Net.Mail.MailMessage ToMailMessage() { System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage(); msg.From = new System.Net.Mail.MailAddress(From); msg.Body = String.IsNullOrEmpty(BodyHtml) ? BodyText : BodyHtml; msg.Subject = Subject; foreach (string toItem in To) msg.To.Add(toItem); foreach (string bccItem in Bcc) msg.Bcc.Add(bccItem); foreach (string ccItem in Cc) msg.CC.Add(ccItem); msg.IsBodyHtml = !String.IsNullOrEmpty(BodyHtml); msg.Priority = System.Net.Mail.MailPriority.Normal; foreach (object item in Attachments) { System.Net.Mail.AlternateView view = new System.Net.Mail.AlternateView( new MemoryStream((item as MimeEntry).Data), (item as MimeEntry).ContentType); msg.AlternateViews.Add(view); } return msg; }
public void SendMail(string Name, string Message, string Gender, string Email, string Copy = "") { int i = 0; string strFrom = ""; string host = ""; string subject = ""; string strCc = ""; string strMessage = GetEmailTemplate(); string DisplayName = ""; if (Settings.Contains("Bcc")) { strCc = Settings["Bcc"].ToString(); } if (Settings.Contains("From")) { strFrom = Settings["From"].ToString(); } if (Settings.Contains("Host")) { host = Settings["Host"].ToString(); } if (Settings.Contains("Subject")) { subject = Settings["Subject"].ToString(); } if (Settings.Contains("DisplayName")) { DisplayName = Settings["DisplayName"].ToString(); } else { DisplayName = PortalSettings.PortalName; } System.Data.DataTable dt = new System.Data.DataTable(); if (string.IsNullOrEmpty(strFrom) || string.IsNullOrEmpty(host) || string.IsNullOrEmpty(host) || string.IsNullOrEmpty(subject)) { throw new Exception("Error al enviar el correo, el módulo no se encuentra configurado correctamente."); } string appPath = string.Format("{0}Resources/Images/", ControlPath); if (appPath.EndsWith("/") == false) { appPath = appPath + Convert.ToString("/"); } strMessage = strMessage.Replace("$TURNO", GetTimeTitle()); strMessage = strMessage.Replace("$GENDER", Gender.ToUpper() == "MASCULINO" ? "estimado" : "estimada"); strMessage = strMessage.Replace("$NOMBRE", Name); strMessage = strMessage.Replace("$MENSAJE", Message); string logo = appPath + Convert.ToString("LogoMail.png"); string appName = appPath + Convert.ToString("AppName.png"); try { // Instantiate a new instance of MailMessage System.Net.Mail.MailMessage mMailMessage = new System.Net.Mail.MailMessage() { //Set the sender address of the mail message From = new System.Net.Mail.MailAddress(strFrom, DisplayName), }; System.Net.Mail.AlternateView av1 = System.Net.Mail.AlternateView.CreateAlternateViewFromString(strMessage, null, System.Net.Mime.MediaTypeNames.Text.Html); System.Net.Mail.LinkedResource linkedResource = new System.Net.Mail.LinkedResource(Server.MapPath(logo)); System.Net.Mail.LinkedResource appNameResource = new System.Net.Mail.LinkedResource(Server.MapPath(appName)); linkedResource.ContentId = "logo"; linkedResource.ContentType.Name = logo; appNameResource.ContentId = "appname"; appNameResource.ContentType.Name = appName; av1.LinkedResources.Add(linkedResource); av1.LinkedResources.Add(appNameResource); mMailMessage.AlternateViews.Add(av1); //Set the recepient address of the mail message string[] arrTo = Email.Split(','); for (i = arrTo.GetLowerBound(0); i <= arrTo.GetUpperBound(0); i++) { if (IsMail(arrTo[i].Trim())) { mMailMessage.To.Add(new System.Net.Mail.MailAddress(arrTo[i].Trim())); } } if (mMailMessage.To.Count == 0) { mMailMessage.To.Add(new System.Net.Mail.MailAddress(strFrom)); } //Check if the cc value is nothing or an empty value if (!string.IsNullOrEmpty(Copy)) { //Set the CC address of the mail message mMailMessage.CC.Add(new System.Net.Mail.MailAddress(Copy)); } //Check if the cc value is nothing or an empty value if (!string.IsNullOrEmpty(strCc)) { //Set the BCC address of the mail message mMailMessage.Bcc.Add(new System.Net.Mail.MailAddress(strCc)); } //Set the subject of the mail message mMailMessage.Subject = subject; //Set the body of the mail message mMailMessage.Body = strMessage; //Set the format of the mail message body as HTML mMailMessage.IsBodyHtml = true; //Instantiate a new instance of SmtpClient System.Net.Mail.SmtpClient emailServer = new System.Net.Mail.SmtpClient(host); //Send the mail message //emailServer.Send(mMailMessage); mMailMessage.Dispose(); } catch (System.Net.Mail.SmtpFailedRecipientsException ehttp) { string err = ""; for (i = 0; i <= ehttp.InnerExceptions.Length; i++) { err = (err + Convert.ToString("SMTP.Send: Error! ")) + ehttp.InnerExceptions[i].StatusCode.ToString() + " Failed to deliver message to " + ehttp.InnerExceptions[i].FailedRecipient.ToString(); } LogError(err); throw new Exception(err); } }
private System.Net.Mail.MailMessage PreparateMailMessage(List <String> Senders, List <String> SendersCC, List <String> SendersBCC, String Subject, String Body, List <ImageAttached> ImagesAttached, bool isHTML, out String Sender) { Sender = String.Empty; System.Net.Mail.MailMessage mailmsg = new System.Net.Mail.MailMessage(); mailmsg.From = new System.Net.Mail.MailAddress(Mail); String SenderTemp = String.Empty; if (Senders != null) { Senders.ForEach(sender => { mailmsg.To.Add(sender); SenderTemp += sender + ";"; }); Sender = SenderTemp; } else { throw new Exception("The sender can not be null"); } if (SendersCC != null) { SendersCC.ForEach(sendercc => mailmsg.CC.Add(sendercc)); } if (SendersBCC != null) { SendersBCC.ForEach(senderbcc => mailmsg.Bcc.Add(senderbcc)); } if (isHTML) { List <ImageAttached> imagesTemp = null; if (Body.Contains("\"data:image/")) { Body = SplitImages(Body, out imagesTemp); } if (ImagesAttached == null && imagesTemp != null) { ImagesAttached = new List <ImageAttached>(); } if (imagesTemp != null) { ImagesAttached.AddRange(imagesTemp); } if (ImagesAttached != null) { System.Net.Mail.AlternateView alternateView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(Body, null, MediaTypeNames.Text.Html); alternateView.ContentId = "htmlview"; alternateView.TransferEncoding = TransferEncoding.SevenBit; ImagesAttached.ForEach(imageAttached => { imageAttached.Tipo.Name = imageAttached.ContentId; System.Net.Mail.LinkedResource linkedResource1 = new System.Net.Mail.LinkedResource(new System.IO.MemoryStream(System.Convert.FromBase64String(imageAttached.ImageBase64)), imageAttached.Tipo); linkedResource1.ContentId = imageAttached.ContentId; linkedResource1.TransferEncoding = TransferEncoding.Base64; alternateView.LinkedResources.Add(linkedResource1); }); mailmsg.AlternateViews.Add(alternateView); } } mailmsg.Subject = Subject; mailmsg.Body = Body; mailmsg.IsBodyHtml = isHTML; mailmsg.Priority = mailPriority; return(mailmsg); }