public MailAttributes Execute(MailAttributes mailAttributes) { var newMailAttributes = new MailAttributes(mailAttributes); foreach (var view in mailAttributes.AlternateViews) { using (var reader = new StreamReader(view.ContentStream)) { var body = reader.ReadToEnd(); if (view.ContentType.MediaType == MediaTypeNames.Text.Html) { var inlinedCssString = PreMailer.MoveCssInline(body); byte[] byteArray = Encoding.UTF8.GetBytes(inlinedCssString.Html); var stream = new MemoryStream(byteArray); var newAlternateView = new AlternateView(stream, MediaTypeNames.Text.Html); newMailAttributes.AlternateViews.Add(newAlternateView); } else { newMailAttributes.AlternateViews.Add(view); } } } return newMailAttributes; }
public static void SendMail(IEmailAccountSettingsProvider provider, string to, string subject, string body, Attachment attach, AlternateView av, bool isHTML) { if (provider.SmtpFrom != String.Empty) { if (provider.SmtpHost == "") return; MailMessage mailMessage = new MailMessage(); mailMessage.From = new MailAddress(provider.SmtpFrom); mailMessage.To.Add(to); mailMessage.Subject = subject; if (av != null) mailMessage.AlternateViews.Add(av); mailMessage.BodyEncoding = Encoding.UTF8; mailMessage.Body = body; if (attach != null) mailMessage.Attachments.Add(attach); if (isHTML) mailMessage.IsBodyHtml = true; SmtpClient smtpClient = new SmtpClient(); smtpClient.Host = provider.SmtpHost; smtpClient.Port = Convert.ToInt32(provider.SmtpPort); smtpClient.UseDefaultCredentials = Convert.ToBoolean(provider.SmtpCredentials); smtpClient.Credentials = new NetworkCredential(provider.SmtpUser, provider.SmtpPwd); smtpClient.EnableSsl = Convert.ToBoolean(provider.SmtpSSL); smtpClient.Send(mailMessage); } }
/// <summary> /// Adds recorded <see cref="LinkedResource"/> image references to the given <see cref="AlternateView"/>. /// </summary> public void AddImagesToView(AlternateView view) { foreach (var image in images) { view.LinkedResources.Add(image.Value); } }
protected virtual MailMessage CreateMailMessage(EmailMessageEntity email) { System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage() { From = email.From.ToMailAddress(), Subject = email.Subject, IsBodyHtml = email.IsBodyHtml, }; System.Net.Mail.AlternateView view = System.Net.Mail.AlternateView.CreateAlternateViewFromString(email.Body.Text !, null, email.IsBodyHtml ? "text/html" : "text/plain"); view.LinkedResources.AddRange(email.Attachments .Where(a => a.Type == EmailAttachmentType.LinkedResource) .Select(a => new System.Net.Mail.LinkedResource(a.File.OpenRead(), MimeMapping.GetMimeType(a.File.FileName)) { ContentId = a.ContentId, })); message.AlternateViews.Add(view); message.Attachments.AddRange(email.Attachments .Where(a => a.Type == EmailAttachmentType.Attachment) .Select(a => new System.Net.Mail.Attachment(a.File.OpenRead(), MimeMapping.GetMimeType(a.File.FileName)) { ContentId = a.ContentId, Name = a.File.FileName, })); message.To.AddRange(email.Recipients.Where(r => r.Kind == EmailRecipientKind.To).Select(r => r.ToMailAddress()).ToList()); message.CC.AddRange(email.Recipients.Where(r => r.Kind == EmailRecipientKind.Cc).Select(r => r.ToMailAddress()).ToList()); message.Bcc.AddRange(email.Recipients.Where(r => r.Kind == EmailRecipientKind.Bcc).Select(r => r.ToMailAddress()).ToList()); return(message); }
//[Test] public static void SendeMail(string url) //Net Mail { var embeddedImage = "C:\\Users\\Wonderson.Chideya\\Downloads\\fonz.jpg"; //Holds message information. System.Net.Mail.MailMessage mailMessage = new MailMessage(); //Add basic information. mailMessage.From = new System.Net.Mail.MailAddress("*****@*****.**"); mailMessage.To.Add("*****@*****.**"); mailMessage.Subject = "mail title"; //Create two views, one text, one HTML. System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString("your content" + "<image src=cid:HDIImage>", null, "text/html"); //Add image to HTML version //System.Net.Mail.LinkedResource imageResource = new System.Net.Mail.LinkedResource(fileImage.PostedFile.FileName); // System.Net.Mail.LinkedResource imageResource = new System.Net.Mail.LinkedResource(@"C:\Users\v-fuzh\Desktop\apple.jpg"); System.Net.Mail.LinkedResource imageResource = new System.Net.Mail.LinkedResource(embeddedImage); imageResource.ContentId = "HDIImage"; htmlView.LinkedResources.Add(imageResource); //Add two views to message. mailMessage.AlternateViews.Add(htmlView); //Send message System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(); smtpClient.Send(mailMessage); }
//Metoda koja kreira mail public static void SendEmail(String ToEmail, String Subj, string Message) { try { System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(); smtpClient.EnableSsl = true; smtpClient.Timeout = 200000; MailMessage MailMsg = new MailMessage(); System.Net.Mime.ContentType HTMLType = new System.Net.Mime.ContentType("text/html"); MailMsg.BodyEncoding = System.Text.Encoding.Default; MailMsg.To.Add(ToEmail); MailMsg.Priority = System.Net.Mail.MailPriority.High; MailMsg.Subject = Subj; MailMsg.Body = Message; MailMsg.IsBodyHtml = true; System.Net.Mail.AlternateView HTMLView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(Message, HTMLType); smtpClient.Send(MailMsg); WriteErrorLog("E-mail uspješno poslan!"); } catch (Exception ex) { WriteErrorLog(ex.InnerException.Message); throw; } }
internal static SerializeableAlternateView GetSerializeableAlternateView(AlternateView av) { if (av == null) return null; var sav = new SerializeableAlternateView(); sav._baseUri = av.BaseUri; sav._contentId = av.ContentId; if (av.ContentStream != null) { var bytes = new byte[av.ContentStream.Length]; av.ContentStream.Read(bytes, 0, bytes.Length); sav._contentStream = new MemoryStream(bytes); } sav._contentType = SerializeableContentType.GetSerializeableContentType(av.ContentType); foreach (LinkedResource lr in av.LinkedResources) sav._linkedResources.Add(SerializeableLinkedResource.GetSerializeableLinkedResource(lr)); sav._transferEncoding = av.TransferEncoding; return sav; }
protected void SendEmail(string emailAddress, String Title, string fullname, string username, string password) { SmtpClient smtp = new SmtpClient(); string MailTemplate = Server.MapPath("~/EmailTemplates/users.htm"); string template = string.Empty; if (File.Exists(MailTemplate)) { template = File.ReadAllText(MailTemplate); } template = template.Replace("<%strUserFullName%>", fullname); template = template.Replace("<%strUserName%>", username); template = template.Replace("<%strPassword%>", password); System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage(); msg.From = new MailAddress("*****@*****.**", "Inter-Agency Coordination Lebanon"); msg.To.Add(emailAddress); msg.Subject = Title; String logo = Server.MapPath("~/EmailTemplates/images/interagency.jpg"); System.Net.Mail.AlternateView htmlView = AlternateView.CreateAlternateViewFromString(template, null, "text/html"); LinkedResource pic1 = new LinkedResource(logo, MediaTypeNames.Image.Jpeg); pic1.ContentId = "logo"; htmlView.LinkedResources.Add(pic1); msg.AlternateViews.Add(htmlView); objEmail.EmailConfig(template, msg); }
protected void SendEmail(string emailAddress, String Title, string subscriber, string strURL) { SmtpClient smtp = new SmtpClient(); string MailTemplate = Server.MapPath("~/EmailTemplates/contactlist.htm"); string template = string.Empty; if (File.Exists(MailTemplate)) { template = File.ReadAllText(MailTemplate); } template = template.Replace("<%strSubscriber%>", subscriber); template = template.Replace("<%strURL%>", strURL); System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage(); msg.From = new MailAddress("your email address", "your email address name"); msg.To.Add(emailAddress); msg.Subject = Title; String logo = Server.MapPath("~/EmailTemplates/images/interagency.jpg"); System.Net.Mail.AlternateView htmlView = AlternateView.CreateAlternateViewFromString(template, null, "text/html"); LinkedResource pic1 = new LinkedResource(logo, MediaTypeNames.Image.Jpeg); pic1.ContentId = "logo"; htmlView.LinkedResources.Add(pic1); msg.AlternateViews.Add(htmlView); objEmail.EmailConfig(template, msg); }
public static MailMessage BuildMessageAndViews(EmailMessage message, out AlternateView textView, out AlternateView htmlView) { var smtpMessage = new MailMessage { BodyEncoding = Encoding.UTF8, From = new MailAddress(message.From) }; if(message.To.Count > 0) smtpMessage.To.Add(string.Join(",", message.To)); if(message.ReplyTo.Count > 0) smtpMessage.ReplyToList.Add(string.Join(",", message.ReplyTo)); if(message.Cc.Count > 0) smtpMessage.CC.Add(string.Join(",", message.Cc)); if(message.Bcc.Count > 0) smtpMessage.Bcc.Add(string.Join(",", message.Bcc)); htmlView = null; textView = null; if (!string.IsNullOrWhiteSpace(message.HtmlBody)) { var mimeType = new ContentType("text/html"); htmlView = AlternateView.CreateAlternateViewFromString(message.HtmlBody, mimeType); smtpMessage.AlternateViews.Add(htmlView); } if (!string.IsNullOrWhiteSpace(message.TextBody)) { const string mediaType = "text/plain"; textView = AlternateView.CreateAlternateViewFromString(message.TextBody, smtpMessage.BodyEncoding, mediaType); textView.TransferEncoding = TransferEncoding.SevenBit; smtpMessage.AlternateViews.Add(textView); } return smtpMessage; }
public string SendEmail(PersonModel model) { var subject = ""; if (model.subject != null) { subject = model.subject; } else { subject = "New Client Appointment"; } string Status = ""; string EmailId = "*****@*****.**"; //Send mail MailMessage mail = new MailMessage(); string FromEmailID = WebConfigurationManager.AppSettings["RegFromMailAddress"]; string FromEmailPassword = WebConfigurationManager.AppSettings["FromEmailPassword"]; SmtpClient smtpClient = new SmtpClient(ConfigurationManager.AppSettings["SmtpServer"]); int _Port = Convert.ToInt32(WebConfigurationManager.AppSettings["Port"].ToString()); Boolean _UseDefaultCredentials = Convert.ToBoolean(WebConfigurationManager.AppSettings["UseDefaultCredentials"].ToString()); Boolean _EnableSsl = Convert.ToBoolean(WebConfigurationManager.AppSettings["EnableSsl"].ToString()); mail.To.Add(new MailAddress(EmailId)); mail.From = new MailAddress(FromEmailID); mail.Subject = subject; string msgbody = ""; msgbody = "<p>Person Name : " + model.Name + "</p>"; msgbody = msgbody + "<p>Email ID : " + model.email + "</p>"; msgbody = msgbody + "<p>Phone Number : " + model.Phone + "</p>"; msgbody = msgbody + "<p>Message : " + model.Message + "</p>"; mail.BodyEncoding = System.Text.Encoding.UTF8; mail.SubjectEncoding = System.Text.Encoding.UTF8; System.Net.Mail.AlternateView plainView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(System.Text.RegularExpressions.Regex.Replace(msgbody, @"<(.|\n)*?>", string.Empty), null, "text/plain"); System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(msgbody, null, "text/html"); mail.AlternateViews.Add(plainView); mail.AlternateViews.Add(htmlView); // mail.Body = msgbody; mail.IsBodyHtml = true; SmtpClient smtp = new SmtpClient(); smtp.DeliveryMethod = SmtpDeliveryMethod.Network; smtp.Host = "smtp.gmail.com"; //_Host; smtp.Port = _Port; //smtp.UseDefaultCredentials = _UseDefaultCredentials; smtp.Credentials = new System.Net.NetworkCredential(FromEmailID, FromEmailPassword);// Enter senders User name and password smtp.EnableSsl = _EnableSsl; smtp.Send(mail); return(Status); }
private MailMessage prepareMail(File_Model file) { MailMessage mailMessage = new MailMessage(); foreach (var address in file.responder.Split(new[] { ";", ",", " " }, StringSplitOptions.RemoveEmptyEntries)) { if (IsValidEmailId(address)) { mailMessage.To.Add(address); } } foreach (var address in file.recipient.Split(new[] { ";", ",", " " }, StringSplitOptions.RemoveEmptyEntries)) { if (IsValidEmailId(address)) { mailMessage.CC.Add(address); } } mailMessage.From = new MailAddress("*****@*****.**"); mailMessage.Subject = "Contract Renewal Announcement"; mailMessage.BodyEncoding = System.Text.Encoding.GetEncoding("utf-8"); //string htmlBody = "Dear HIT, <br/><br/>Please kindly authorize"; string htmlBody = "Dear Sir or Madam,<br/><br/>Please be informed that this contract or agreement is going to be expired on " + file.expire_Date.ToShortDateString() + ". Please renew the contract or agreement before the deadline. <br/><br/>Regards, <br/> Legal & Compliance Department"; mailMessage.Attachments.Add(new Attachment(new MemoryStream(file.file_Data, false), file.file_Name, "application/pdf")); System.Net.Mail.AlternateView plainView = System.Net.Mail.AlternateView.CreateAlternateViewFromString (System.Text.RegularExpressions.Regex.Replace(htmlBody, @"<(.|\n)*?>", string.Empty), null, "text/plain"); System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(htmlBody, null, "text/html"); mailMessage.AlternateViews.Add(plainView); mailMessage.AlternateViews.Add(htmlView); mailMessage.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure; return(mailMessage); }
// This function contains the logic to send mail. public static void SendEmail(String ToEmail, String Subj, string Message) { try { System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(); smtpClient.EnableSsl = true; smtpClient.Timeout = 200000; MailMessage MailMsg = new MailMessage(); System.Net.Mime.ContentType HTMLType = new System.Net.Mime.ContentType("text/html"); string strBody = "This is a test mail."; MailMsg.BodyEncoding = System.Text.Encoding.Default; MailMsg.To.Add(ToEmail); MailMsg.Priority = System.Net.Mail.MailPriority.High; MailMsg.Subject = "Subject - Window Service"; MailMsg.Body = strBody; MailMsg.IsBodyHtml = true; System.Net.Mail.AlternateView HTMLView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(strBody, HTMLType); smtpClient.Send(MailMsg); WriteErrorLog("Mail sent successfully!"); } catch (Exception ex) { WriteErrorLog(ex.InnerException.Message); throw; } }
private static MimeMailMessage getMimeMailMessage(EmailSettingInfo emailSetting, EmailInfo email, String emailBodyOrg, List <MailAddress> mailList) { String companyName = email.CompanyName.Split('|')[0].Split(':')[0].Trim(); email.CompanyName = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(companyName.ToLower()); String emailBody = emailBodyOrg.Replace("{Company}", email.CompanyName).Replace("\r\n", "<br />"); MimeMailMessage mailMessage = new MimeMailMessage(); mailMessage.From = new MimeMailAddress("*****@*****.**"); mailMessage.Subject = emailSetting.Subject; mailMessage.BodyEncoding = System.Text.Encoding.UTF8; mailMessage.IsBodyHtml = true; mailMessage.Body = emailBody; System.Net.Mail.AlternateView plainView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(System.Text.RegularExpressions.Regex.Replace(emailBody, @"<(.|\n)*?>", string.Empty), null, "text/plain"); System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(emailBody, null, "text/html"); mailMessage.AlternateViews.Add(plainView); mailMessage.AlternateViews.Add(htmlView); foreach (MailAddress emailAddress in mailList) { mailMessage.To.Add(emailAddress); } return(mailMessage); }
protected void btnEmail_Click(object sender, EventArgs e) { try { System.Net.Mail.AlternateView htmlView = null; string from = "*****@*****.**"; using (MailMessage mail = new MailMessage(from, txtEmail.Text.Trim())) { mail.Subject = "Json File"; htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString("<html><body><div style='border-style:solid;border-width:5px;border-radius: 10px; padding-left: 10px;margin: 20px; font-size: 18px;'> <p style='font-family: Vladimir Script;font-weight: bold; color: #f7d722;font-size: 48px;'>Kindly find the Attachment.</p><hr><div width=40%;> <p style='font-size: 20px;'>Thanks</div></body></html>", null, "text/html"); mail.AlternateViews.Add(htmlView); mail.IsBodyHtml = true; System.Net.Mime.ContentType contentType = new System.Net.Mime.ContentType(); contentType.MediaType = System.Net.Mime.MediaTypeNames.Application.Octet; contentType.Name = "New-Assign04.json"; mail.Attachments.Add(new Attachment(Server.MapPath("~/App_Data/New-Assign04.json"), contentType)); SmtpClient smtp = new SmtpClient(); smtp.Host = "smtp-mail.outlook.com"; smtp.EnableSsl = true; NetworkCredential networkCredential = new NetworkCredential("*****@*****.**", "comp229pwd"); // username and password smtp.UseDefaultCredentials = true; smtp.Credentials = networkCredential; smtp.Port = 587; smtp.Send(mail); string message = "alert('Email Sent Successfully.')"; ScriptManager.RegisterClientScriptBlock((sender as Control), this.GetType(), "alert", message, true); } } catch (System.Exception ex) { string message = "alert('Email Sending Failed.')"; ScriptManager.RegisterClientScriptBlock((sender as Control), this.GetType(), "alert", message, true); } }
public void Add(System.Net.Mail.AlternateView alternate) { base.Add(new MailMessageAlternateView() { Content = alternate.ContentStream.ToByteArray(), ContentType = alternate.ContentType.MediaType }); }
private void SendGroupMail(string mailid, string name, string groupname) { try { SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]); string mailfrom = ConfigurationManager.AppSettings["mailfrom"]; string mailServer = ConfigurationManager.AppSettings["mailServer"]; string username = ConfigurationManager.AppSettings["UserName"]; string Password = ConfigurationManager.AppSettings["Password"]; string Port = ConfigurationManager.AppSettings["Port"]; string MailURL = ConfigurationManager.AppSettings["MailURL"]; string DisplayName = ConfigurationManager.AppSettings["DisplayName"]; string MailSSL = ConfigurationManager.AppSettings["MailSSL"]; string MailTo = mailid; string Mailbody = ""; SmtpClient clientip = new SmtpClient(mailServer); clientip.Port = Convert.ToInt32(Port); clientip.UseDefaultCredentials = true; if (MailSSL != "0") { clientip.EnableSsl = true; } try { MailMessage Rmm2 = new MailMessage(); Rmm2.IsBodyHtml = true; Rmm2.From = new System.Net.Mail.MailAddress(mailfrom); Rmm2.Body = Mailbody.ToString(); //FOR AUTO-JOIN System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString("<b>Skorkel group joining invitation</b>" + "<br><br>" + " " + name + " " + "You are successfuly join the" + " " + groupname + " " + "group" + "<br><br><br>" + "Thanks," + "<br>" + "The Skorkel Team", null, "text/html"); Rmm2.To.Clear(); Rmm2.To.Add(MailTo); Rmm2.Subject = "Skorkel group joining invitation"; Rmm2.AlternateViews.Add(htmlView); Rmm2.IsBodyHtml = true; clientip.Send(Rmm2); Rmm2.To.Clear(); } catch (FormatException ex) { ex.Message.ToString(); return; } catch (SmtpException ex) { ex.Message.ToString(); return; } finally { conn.Close(); } } catch (Exception ex) { ex.Message.ToString(); } }
public static void SendEmailWithAttachment(string MailTo, string subject, string body, string fileName) { try { Attachment data = new Attachment(HttpContext.Current.Server.MapPath("~\\tmp\\") + fileName, MediaTypeNames.Application.Octet); string mailfrom = ConfigurationManager.AppSettings["mailfrom"]; string mailServer = ConfigurationManager.AppSettings["mailServer"]; string username = ConfigurationManager.AppSettings["UserName"]; string Password = ConfigurationManager.AppSettings["Password"]; string Port = ConfigurationManager.AppSettings["Port"]; string MailURL = ConfigurationManager.AppSettings["MailURL"]; string MailSSL = ConfigurationManager.AppSettings["MailSSL"]; string Mailbody = ""; body = body.Replace("{RedirectURL}", MailURL); System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html); SmtpClient clientip = new SmtpClient(mailServer); clientip.Port = Convert.ToInt32(Port); clientip.UseDefaultCredentials = false; if (MailSSL != "0") { clientip.EnableSsl = true; } clientip.Credentials = new System.Net.NetworkCredential(username, Password); string DisplayName = ConfigurationManager.AppSettings["DisplayName"]; try { using (MailMessage Rmm2 = new MailMessage()) { Rmm2.IsBodyHtml = true; Rmm2.From = new System.Net.Mail.MailAddress(mailfrom, DisplayName); Rmm2.Body = Mailbody.ToString(); Rmm2.Attachments.Add(data); Rmm2.To.Clear(); Rmm2.To.Add(MailTo); Rmm2.Subject = subject; Rmm2.AlternateViews.Add(htmlView); Rmm2.IsBodyHtml = true; clientip.Send(Rmm2); } } catch (FormatException ex) { ex.Message.ToString(); return; } catch (SmtpException ex) { ex.Message.ToString(); return; } } catch (Exception ex) { ex.Message.ToString(); } }
// add calendar attachment public static System.Net.Mail.AlternateView MakeCalendarView(DateTime start, DateTime end, string subject, string description, string location, string organiserName, string organiserEmail) { string ics = MakeICSFile(start, end, subject, description, location, organiserName, organiserEmail); System.Net.Mime.ContentType contype = new System.Net.Mime.ContentType("text/calendar"); contype.Parameters.Add("method", "REQUEST"); contype.Parameters.Add("name", "Meeting.ics"); System.Net.Mail.AlternateView avCal = System.Net.Mail.AlternateView.CreateAlternateViewFromString(ics, contype); return(avCal); }
private SerializableAlternateView(AlternateView view) { BaseUri = view.BaseUri; LinkedResources = new SerializableLinkedResourceCollection(); foreach (LinkedResource res in view.LinkedResources) LinkedResources.Add(res); ContentId = view.ContentId; ContentStream = new MemoryStream(); view.ContentStream.CopyTo(ContentStream); view.ContentStream.Position = 0; ContentType = view.ContentType; TransferEncoding = view.TransferEncoding; }
private static void setBody(EmailInfo email, String emailBodyOrg, ref MailMessage mailMessage) { String companyName = email.CompanyName.Split('|')[0].Split(':')[0].Trim(); email.CompanyName = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(companyName.ToLower()); String emailBody = emailBodyOrg.Replace("{Company}", email.CompanyName).Replace("\r\n", "<br />"); System.Net.Mail.AlternateView plainView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(System.Text.RegularExpressions.Regex.Replace(emailBody, @"<(.|\n)*?>", string.Empty), null, "text/plain"); System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(emailBody, null, "text/html"); mailMessage.AlternateViews.Add(plainView); mailMessage.AlternateViews.Add(htmlView); }
public string SendRegistrationEmailToAdmin(PersonModel model) { var subject = ""; subject = "New user registered for RPL Canada"; string Status = ""; string EmailId = "*****@*****.**";// "*****@*****.**"; //Send mail MailMessage mail = new MailMessage(); string FromEmailID = WebConfigurationManager.AppSettings["FromEmailID"]; string FromEmailPassword = WebConfigurationManager.AppSettings["FromEmailPassword"]; string ToEmailID = WebConfigurationManager.AppSettings["FromEmailID"]; SmtpClient smtpClient = new SmtpClient(ConfigurationManager.AppSettings["SmtpServer"]); int _Port = Convert.ToInt32(WebConfigurationManager.AppSettings["Port"].ToString()); Boolean _UseDefaultCredentials = Convert.ToBoolean(WebConfigurationManager.AppSettings["UseDefaultCredentials"].ToString()); Boolean _EnableSsl = Convert.ToBoolean(WebConfigurationManager.AppSettings["EnableSsl"].ToString()); mail.To.Add(new MailAddress(EmailId)); mail.From = new MailAddress(FromEmailID); mail.Subject = subject; string msgbody = ""; msgbody += "<b>Name</b> : " + model.FirstName + " " + model.LastName + "<br>"; msgbody += "<b>Email</b> : " + model.Email + "<br>"; msgbody += "<b>Phone No</b>: " + model.PhoneNo + "<br>"; msgbody += "<b>Brokerage</b> : " + model.Brokerage + "<br>"; mail.BodyEncoding = System.Text.Encoding.UTF8; mail.SubjectEncoding = System.Text.Encoding.UTF8; System.Net.Mail.AlternateView plainView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(System.Text.RegularExpressions.Regex.Replace(msgbody, @"<(.|\n)*?>", string.Empty), null, "text/plain"); System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(msgbody, null, "text/html"); mail.AlternateViews.Add(plainView); mail.AlternateViews.Add(htmlView); // mail.Body = msgbody; mail.IsBodyHtml = true; SmtpClient smtp = new SmtpClient(); smtp.DeliveryMethod = SmtpDeliveryMethod.Network; smtp.Host = "smtp.gmail.com"; //_Host; smtp.Port = _Port; //smtp.UseDefaultCredentials = _UseDefaultCredentials; smtp.Credentials = new System.Net.NetworkCredential(FromEmailID, FromEmailPassword);// Enter senders User name and password smtp.EnableSsl = _EnableSsl; smtp.Send(mail); Status = "success"; return(Status); }
public static void SendEmail(string FromEmail, string FromDispalyName, string ToList, string Subject, string HtmBody, string BCCList = "", AlternateView view = null) { MailMessage msgMail = new MailMessage(); if (view != null) msgMail.AlternateViews.Add(view); if (!string.IsNullOrEmpty(ToList)) { string[] toList = ToList.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); foreach (string s in toList) { msgMail.To.Add(s); } } if (!string.IsNullOrEmpty(BCCList)) { string[] bccList = BCCList.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); foreach (string s in bccList) { msgMail.Bcc.Add(s); } } msgMail.From = new MailAddress(FromEmail, FromDispalyName, Encoding.UTF8); msgMail.Subject = Subject; msgMail.Body = HtmBody; msgMail.IsBodyHtml = true; msgMail.Priority = MailPriority.High; msgMail.DeliveryNotificationOptions = DeliveryNotificationOptions.Never; SmtpClient Client = new SmtpClient(SystemConfigs.SMTPServer) { Port = Convert.ToInt32(SystemConfigs.SMTPPort), EnableSsl = Convert.ToBoolean(SystemConfigs.SMTPIsSSL) }; string UserName = SystemConfigs.SMTPUserName; string Password = SystemConfigs.SMTPPassword; if (!string.IsNullOrEmpty(UserName)) { NetworkCredential Ceredentials = new NetworkCredential(UserName, Password); Client.Credentials = Ceredentials; } else { Client.Credentials = CredentialCache.DefaultNetworkCredentials; } Client.Send(msgMail); }
internal static void PollingEmail(string connString, String code) { Boolean success = false; Utilities.Utilities.Log(message: "Sending emails Start ... ", isWriteLine: true, addTime: true); EmailSettingInfo emailSetting = DataOperation.GetEmailSetting(connString, code); Utilities.Utilities.Log(message: $"[{emailSetting.Code}] [{emailSetting.Name}] ... ", isWriteLine: false, addTime: true); MailMessage mailMessage = getMailMessage(emailSetting); SmtpClient smtpClient = getsmtpClient(); String emailBodyOrg = System.IO.File.ReadAllText(emailSetting.FileFullName); List <EmailInfo> emails = DataOperation.GetEmails(connString, code); Int32 count = (Int32)(emails.Count * emailSetting.SendPercentage / 100); Utilities.Utilities.Log(message: $"[{count}/{emails.Count}]", isWriteLine: true); foreach (EmailInfo email in emails.Take(count)) { //email.Email = "*****@*****.**"; success = false; Utilities.Utilities.Log(message: $"Sending [{email.Email}] ... ", isWriteLine: false, addTime: true); email.Code = code; email.CompanyName = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(email.CompanyName.ToLower()); String emailBody = emailBodyOrg.Replace("{Company}", email.CompanyName).Replace("\r\n", "<br />"); string[] toEmails = email.Email.Split(';'); mailMessage.To.Clear(); foreach (String toEmail in toEmails) { try { mailMessage.To.Add(toEmail); } catch (Exception) { } } System.Net.Mail.AlternateView plainView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(System.Text.RegularExpressions.Regex.Replace(emailBody, @"<(.|\n)*?>", string.Empty), null, "text/plain"); System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(emailBody, null, "text/html"); mailMessage.AlternateViews.Add(plainView); mailMessage.AlternateViews.Add(htmlView); try { smtpClient.Send(mailMessage); success = true; } catch (Exception ex) { email.Comments = ex.Message; } success = DataOperation.UpdateEmail(connString, email); Utilities.Utilities.Log(message: success ? $"[Done]" : "[X]", isWriteLine: true, addTime: false); } smtpClient.Dispose(); mailMessage.Dispose(); }
public AlternateView GetAlternateView() { var sav = new AlternateView(ContentStream) { BaseUri = BaseUri, ContentId = ContentId, ContentType = ContentType.GetContentType(), TransferEncoding = TransferEncoding, }; foreach (var linkedResource in LinkedResources) sav.LinkedResources.Add(linkedResource.GetLinkedResource()); return sav; }
internal AlternateView GetAlternateView() { var sav = new AlternateView(_contentStream); sav.BaseUri = _baseUri; sav.ContentId = _contentId; sav.ContentType = _contentType.GetContentType(); foreach (SerializeableLinkedResource lr in _linkedResources) sav.LinkedResources.Add(lr.GetLinkedResource()); sav.TransferEncoding = _transferEncoding; return sav; }
// This function contains the logic to send mail. public static void SendEmail(String ToEmail, String mgrEmail, String empname, string empgpn, int count1, int count2, int count3) { try { System.Net.Mail.SmtpClient smtpServer = new System.Net.Mail.SmtpClient(); smtpServer.Host = ConfigurationManager.AppSettings["SMTPServer"].ToString(); smtpServer.UseDefaultCredentials = false; smtpServer.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["SMTPUserName"].ToString(), ConfigurationManager.AppSettings["SMTPPassword"].ToString(), ConfigurationManager.AppSettings["SMTPDomain"].ToString()); smtpServer.DeliveryMethod = SmtpDeliveryMethod.Network; smtpServer.Port = Convert.ToInt32(ConfigurationManager.AppSettings["SMTPPort"]); string MailDisplayName = ConfigurationManager.AppSettings["MailDisplayName"].ToString(); string MailFrom = ConfigurationManager.AppSettings["MailFrom"].ToString(); string filepath = ConfigurationManager.AppSettings["filepath"].ToString(); MailMessage MailMsg = new MailMessage(); System.Net.Mime.ContentType HTMLType = new System.Net.Mime.ContentType("text/html"); string strBody = Common.createbody(empname, count1, count2, count3); MailMsg.BodyEncoding = System.Text.Encoding.Default; MailMsg.From = new MailAddress("*****@*****.**", MailDisplayName); MailMsg.Sender = new MailAddress(MailFrom); MailMsg.CC.Add(mgrEmail); MailMsg.To.Add(ToEmail); MailMsg.Priority = System.Net.Mail.MailPriority.High; MailMsg.Subject = "CheckIn/CheckOut Report For month " + (DateTime.Now.Month).ToString(); MailMsg.Body = strBody; MailMsg.Attachments.Add(new Attachment(filepath + empname + " (Attendance).xls")); MailMsg.IsBodyHtml = true; System.Net.Mail.AlternateView HTMLView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(strBody, HTMLType); smtpServer.Send(MailMsg); WriteErrorLog("Mail sent successfully!"); MailMsg.Dispose(); } catch (Exception ex) { WriteErrorLog(ex.InnerException.Message); throw; } }
public SerializableAlternateView(AlternateView alternativeView) { BaseUri = alternativeView.BaseUri; ContentId = alternativeView.ContentId; ContentType = new SerializableContentType(alternativeView.ContentType); TransferEncoding = alternativeView.TransferEncoding; if (alternativeView.ContentStream != null) { byte[] bytes = new byte[alternativeView.ContentStream.Length]; alternativeView.ContentStream.Read(bytes, 0, bytes.Length); ContentStream = new MemoryStream(bytes); } foreach (var lr in alternativeView.LinkedResources) LinkedResources.Add(new SerializableLinkedResource(lr)); }
private void genrateEmail(string receiverAddr, string subjectMail, string mailMsgBody) { System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(); smtpClient.EnableSsl = true; MailMessage mailMesg = new MailMessage(); System.Net.Mime.ContentType XMLtype = new System.Net.Mime.ContentType("text/html"); mailMesg.BodyEncoding = System.Text.Encoding.Default; mailMesg.To.Add(receiverAddr); mailMesg.Priority = System.Net.Mail.MailPriority.High; mailMesg.Subject = subjectMail; mailMesg.Body = mailMsgBody; mailMesg.IsBodyHtml = true; System.Net.Mail.AlternateView alternateView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(mailMsgBody, XMLtype); smtpClient.Send(mailMesg); LogService("Mail Sent"); }
private MailMessage GenerateHtmlMessage(string from, string to, string subject, string content, string[] attachmentFilepaths) { MailMessage mail = new MailMessage(); mail.From = new MailAddress(from); mail.To.Add(to); mail.Subject = subject; string body = null; if (attachmentFilepaths != null && attachmentFilepaths.Length > 0) { StringBuilder sb = new StringBuilder(); sb.Append("MIME-Version: 1.0\r\n"); sb.Append("Content-Type: multipart/mixed; boundary=unique-boundary-1\r\n"); sb.Append("\r\n"); sb.Append("This is a multi-part message in MIME format.\r\n"); sb.Append("--unique-boundary-1\r\n"); sb.Append("Content-Type: text/html\r\n"); //could use text/plain as well here if you want a plaintext message sb.Append("Content-Transfer-Encoding: 7Bit\r\n\r\n"); sb.Append(content); if (!content.EndsWith("\r\n")) sb.Append("\r\n"); sb.Append("\r\n\r\n"); foreach (string filepath in attachmentFilepaths) { sb.Append(GenerateRawAttachement(filepath)); } body = sb.ToString(); } else { body = "Content-Type: text/html\r\nContent-Transfer-Encoding: 7Bit\r\n\r\n" + content; } //input your certification and private key. X509Certificate2 cert = new X509Certificate2("emailcertification.pfx", "6522626", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet); ContentInfo contentInfo = new ContentInfo(Encoding.UTF8.GetBytes(body)); SignedCms signedCms = new SignedCms(contentInfo, false); CmsSigner Signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, cert); signedCms.ComputeSignature(Signer); byte[] signedBytes = signedCms.Encode(); MemoryStream stream = new MemoryStream(signedBytes); AlternateView view = new AlternateView(stream, "application/pkcs7-mime; smime-type=signed-data;name=smime.p7m"); mail.AlternateViews.Add(view); return mail; }
public static SystemMailMessage ToMailMessage(this MailMessage mail) { var message = new SystemMailMessage { DeliveryNotificationOptions = mail.DeliveryNotificationOptions, IsBodyHtml = mail.IsBodyHtml, Priority = mail.Priority, Body = mail.Body, Subject = mail.Subject, BodyEncoding = mail.BodyEncoding, SubjectEncoding = mail.SubjectEncoding, HeadersEncoding = mail.HeadersEncoding, }; if (mail.From != null) { message.From = new MailAddress(mail.From); } if (mail.Sender != null) { message.Sender = new MailAddress(mail.Sender); } foreach (var alternateView in mail.AlternateViews) { var mimeType = new ContentType(alternateView.ContentType); var systemAlternateView = SystemAlternateView.CreateAlternateViewFromString(alternateView.Content, mimeType); message.AlternateViews.Add(systemAlternateView); } mail.To.ForEach(a => message.To.Add(new MailAddress(a))); mail.ReplyTo.ForEach(a => message.ReplyToList.Add(new MailAddress(a))); mail.Bcc.ForEach(a => message.Bcc.Add(new MailAddress(a))); mail.Cc.ForEach(a => message.CC.Add(new MailAddress(a))); foreach (var header in mail.Headers) { message.Headers[header.Key] = header.Value; } return(message); }
public ActionResult About() { MailMessage email = new MailMessage(); email.To.Add(new MailAddress("*****@*****.**")); email.To.Add(new MailAddress("*****@*****.**")); email.From = new MailAddress("*****@*****.**"); email.Subject = "Mensaje de prueba"; StringBuilder strHtm = new StringBuilder(); var uno = HttpRuntime.AppDomainAppPath; strHtm.Append(System.IO.File.ReadAllText(uno + "/Views/Home/Index.cshtml", Encoding.UTF8)); System.Net.Mail.AlternateView alterView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(strHtm.ToString(), Encoding.UTF8, "text/html"); email.AlternateViews.Add(alterView); //email.Body = strHtm.ToString(); email.IsBodyHtml = true; email.Priority = MailPriority.High; SmtpClient smtp = new SmtpClient(); smtp.Host = "10.49.10.55"; smtp.Port = 25; smtp.EnableSsl = false; smtp.Credentials = new NetworkCredential("S001846", ""); try{ smtp.Send(email); email.Dispose(); } catch (Exception ex) { } ViewBag.Message = "Your application description page."; return(View()); }
public static AlternateView CreateView( IHtmlDocument document ) { var stream = new MemoryStream(); document.Render( stream, Encoding.UTF8 ); stream.Seek( 0, SeekOrigin.Begin ); var resources = GetResources( document ); var view = new AlternateView( stream, "text/html" ); view.TransferEncoding = TransferEncoding.Base64; view.BaseUri = document.DocumentUri; foreach ( var r in resources ) view.LinkedResources.Add( r ); return view; }
public static bool SendMail(string Para, string asunto, string html) { try { System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader(); SmtpClient clientDetails = new SmtpClient(); clientDetails.Port = Convert.ToInt32((string)settingsReader.GetValue("Port", typeof(String))); clientDetails.Host = (string)settingsReader.GetValue("Host", typeof(String)); clientDetails.EnableSsl = true; clientDetails.DeliveryMethod = SmtpDeliveryMethod.Network; clientDetails.UseDefaultCredentials = false; clientDetails.Credentials = new NetworkCredential((string)settingsReader.GetValue("UserMail", typeof(String)), (string)settingsReader.GetValue("PasswordMail", typeof(String))); System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(html, null, "text/html"); //Add image to HTML version System.Net.Mail.LinkedResource imageResource = new System.Net.Mail.LinkedResource(System.Web.HttpContext.Current.Server.MapPath("~/Scripts/Images/logo_asocajas.png")); imageResource.ContentId = "HDIImage"; htmlView.LinkedResources.Add(imageResource); //Add two views to message. //Detalle Mensaje MailMessage mailDetails = new MailMessage(); mailDetails.From = new MailAddress((string)settingsReader.GetValue("UserMail", typeof(String))); mailDetails.To.Add(Para); mailDetails.Subject = asunto; mailDetails.IsBodyHtml = true; mailDetails.AlternateViews.Add(htmlView); //mailDetails.Body = html; clientDetails.Send(mailDetails); return(true); } catch (Exception) { return(false); } }
public static void MailGonder(string ToAddress, string BodyText, string Subject, string fromadress = "Karatekin Üniversitesi - Bilgi İşlem Daire Başkanlığı Yazılım Grubu <*****@*****.**>") { string FromAddress = fromadress; System.Net.Mail.MailMessage mailMsg = new System.Net.Mail.MailMessage(); mailMsg.From = new MailAddress(FromAddress); mailMsg.To.Add(new MailAddress(ToAddress)); mailMsg.Subject = Subject; mailMsg.IsBodyHtml = true; mailMsg.BodyEncoding = System.Text.Encoding.GetEncoding("ISO-8859-9"); System.Net.Mail.AlternateView plainView = System.Net.Mail.AlternateView.CreateAlternateViewFromString (System.Text.RegularExpressions.Regex.Replace(BodyText, @"<(.|\n)*?>", string.Empty), null, "text/plain"); System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(BodyText, null, "text/html"); mailMsg.AlternateViews.Add(plainView); mailMsg.AlternateViews.Add(htmlView); //System.Net.Mail.Attachment attachment; //attachment = new System.Net.Mail.Attachment(attac); //mailMsg.Attachments.Add(attachment); // Smtp configuration SmtpClient smtp = new SmtpClient(); smtp.Host = "mail.karatekin.edu.tr"; smtp.Port = 25; //smtp.EnableSsl = true; smtp.Credentials = new System.Net.NetworkCredential("*****@*****.**", "1973aSD"); //smtp.EnableSsl = true; try { smtp.Send(mailMsg); } catch (Exception) { } }
public static AlternateView CreateAlternateViewFromString (string content, Encoding encoding, string mediaType) { if (content == null) throw new ArgumentNullException ("content"); if (encoding == null) encoding = Encoding.UTF8; MemoryStream ms = new MemoryStream (encoding.GetBytes (content)); ContentType ct = new ContentType (); ct.MediaType = mediaType; ct.CharSet = encoding.HeaderName; AlternateView av = new AlternateView (ms, ct); av.TransferEncoding = TransferEncoding.QuotedPrintable; return av; }
/// <summary> /// Creates an instance of the AlternateView class used by the MailMessage class /// to store alternate views of the mail message's content. /// </summary> /// <param name="part">The MIME body part to create the alternate view from.</param> /// <param name="bytes">An array of bytes composing the content of the /// alternate view</param> /// <returns>An initialized instance of the AlternateView class</returns> private static AlternateView CreateAlternateView(Bodypart part, byte[] bytes) { MemoryStream stream = new MemoryStream(bytes); string contentType = part.Type.ToString().ToLower() + "/" + part.Subtype.ToLower(); AlternateView view = new AlternateView(stream, new System.Net.Mime.ContentType(contentType)); try { view.ContentId = ParseMessageId(part.Id); } catch {} return view; }
public string SendNewsLetter(NewsLetterModel model) { if (model.Logopath == null || model.Logopath == "") { model.Logopath = "http://kamaljitsingh.ca/images/logo.png"; } if (model.PropertyPhoto == null || model.PropertyPhoto == "") { model.PropertyPhoto = "http://kamaljitsingh.ca/images/img1.png"; } string Status = ""; // string EmailId = "*****@*****.**"; string msgbody = ""; var Template = ""; if (model.NewsletterType == "First_nwslettr") { Template = "Templates/FirstNewsLetter.html"; } else if (model.NewsletterType == "Second_nwslettr") { Template = "Templates/SecondNewsLetter.html"; } else if (model.NewsletterType == "Thirld_nwslettr") { Template = "Templates/ThirldNewsLetter.html"; } else if (model.NewsletterType == "Fourth_nwslettr") { Template = "Templates/FourthNewsLetter.html"; } else if (model.NewsletterType == "Fifth_nwslettr") { Template = "Templates/FifthNewLetter.html"; } else if (model.NewsletterType == "Sixth_nwslettr") { Template = "Templates/SixNewLetter.html"; } else if (model.NewsletterType == "Seventh_nwslettr") { Template = "Templates/SeventhNewsLetter.html"; } else if (model.NewsletterType == "Eighth_nwslettr") { Template = "Templates/EighthNewsLetter.html"; } else if (model.NewsletterType == "Ninth_nwslettr") { Template = "Templates/NinthNewsLetter.html"; } else if (model.NewsletterType == "Tenth_nwslettr") { Template = "Templates/TenthNewsLetter.html"; } else if (model.NewsletterType == "Eleventh_nwslettr") { Template = "Templates/EleventhNewsLetter.html"; } else if (model.NewsletterType == "Twelveth_nwslettr") { Template = "Templates/TwelvethNewsLetter.html"; } else if (model.NewsletterType == "Thirteenth_nwslettr") { Template = "Templates/ThirteenthNewsLetter.html"; } else if (model.NewsletterType == "Fourteenth_nwslettr") { Template = "Templates/FourteenthNewsLetter.html"; } else if (model.NewsletterType == "Fifteenth_nwslettr") { Template = "Templates/FifteenthNewsLetter.html"; } else if (model.NewsletterType == "Sixteenth_nwslettr") { Template = "Templates/SixteenthNewsLetter.html"; } else if (model.NewsletterType == "Seventeenth_nwslettr") { Template = "Templates/SeventeenthNewsLetter.html"; } else if (model.NewsletterType == "Eightteenth_nwslettr") { Template = "Templates/EightteenthNewsLetter.html"; } else if (model.NewsletterType == "Ninteenth_nwslettr") { Template = "Templates/NinteenthNewsLetter.html"; } else if (model.NewsletterType == "Twentieth_nwslettr") { Template = "Templates/TwentiethNewsLetter.html"; } else if (model.NewsletterType == "TwentyOne_nwslettr") { Template = "Templates/TwentyOneNewsLetter.html"; } using (StreamReader reader = new StreamReader(Path.Combine(HttpRuntime.AppDomainAppPath, Template))) { msgbody = reader.ReadToEnd(); //Replace UserName and Other variables available in body Stream msgbody = msgbody.Replace("{PropertyPhoto}", model.PropertyPhoto); msgbody = msgbody.Replace("{logopath}", model.Logopath); msgbody = msgbody.Replace("{FirstContent}", model.FirstContent); msgbody = msgbody.Replace("{SecondContent}", model.SecondContent); msgbody = msgbody.Replace("{ThirdContent}", model.ThirldContent); } //Send mail MailMessage mail = new MailMessage(); string FromEmailID = WebConfigurationManager.AppSettings["RegFromMailAddress"]; string FromEmailPassword = WebConfigurationManager.AppSettings["RegPassword"]; SmtpClient smtpClient = new SmtpClient(ConfigurationManager.AppSettings["SmtpServer"]); int _Port = Convert.ToInt32(WebConfigurationManager.AppSettings["Port"].ToString()); Boolean _UseDefaultCredentials = Convert.ToBoolean(WebConfigurationManager.AppSettings["UseDefaultCredentials"].ToString()); Boolean _EnableSsl = Convert.ToBoolean(WebConfigurationManager.AppSettings["EnableSsl"].ToString()); mail.To.Add(new MailAddress(model.Email)); mail.From = new MailAddress(FromEmailID); mail.Subject = "News Letter"; mail.BodyEncoding = System.Text.Encoding.UTF8; mail.SubjectEncoding = System.Text.Encoding.UTF8; System.Net.Mail.AlternateView plainView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(System.Text.RegularExpressions.Regex.Replace(msgbody, @"<(.|\n)*?>", string.Empty), null, "text/plain"); System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(msgbody, null, "text/html"); mail.AlternateViews.Add(plainView); mail.AlternateViews.Add(htmlView); // mail.Body = msgbody; mail.IsBodyHtml = true; SmtpClient smtp = new SmtpClient(); smtp.DeliveryMethod = SmtpDeliveryMethod.Network; smtp.Host = "smtp.gmail.com"; //_Host; smtp.Port = _Port; //smtp.UseDefaultCredentials = _UseDefaultCredentials; smtp.Credentials = new System.Net.NetworkCredential(FromEmailID, FromEmailPassword);// Enter senders User name and password smtp.EnableSsl = _EnableSsl; smtp.Send(mail); return(Status); }
public static AlternateView CreateAlternateViewFromString(string content, Encoding contentEncoding, string mediaType) { AlternateView view = new AlternateView(); view.SetContentFromString(content, contentEncoding, mediaType); return view; }
/// <summary> /// Adds LinkedResources to the mailPart /// </summary> public virtual List<LinkedResource> PopulateLinkedResources(AlternateView mailPart, Dictionary<string, string> resources) { if (resources == null || resources.Count == 0) { return new List<LinkedResource>(); } var linkedResources = LinkedResourceProvider.GetAll(resources); linkedResources.ForEach(resource => mailPart.LinkedResources.Add(resource)); return linkedResources; }
public ActionResult Support(SupportModel Model) { //Save Support Form Support spt = new Support(); var isSaveSuccess = true; if (isSaveSuccess) { spt.Name = Model.Name; } spt.Email = Model.Email; spt.PhoneNo = Model.PhoneNo; spt.Subject = Model.Subject; spt.DescribeYourIssue = Model.DescribeYourIssue; dba.Supports.InsertOnSubmit(spt); dba.SubmitChanges(); if (ModelState.IsValid) { try { MailMessage mail = new MailMessage(); SmtpClient client = new SmtpClient(); mail.To.Add("*****@*****.**"); mail.From = new MailAddress("*****@*****.**"); client.Port = 587; client.Host = "smtp.gmail.com"; client.EnableSsl = true; client.Timeout = 10000; client.DeliveryMethod = SmtpDeliveryMethod.Network; client.UseDefaultCredentials = false; client.Credentials = new System.Net.NetworkCredential("*****@*****.**", "testing@123"); mail.Subject = Model.Subject; string msgbody = ""; msgbody = "Hi "; string Template = ""; Template = "Templates/Support.html"; using (StreamReader reader = new StreamReader(Path.Combine(HttpRuntime.AppDomainAppPath, Template))) { msgbody = reader.ReadToEnd(); //Replace UserName and Other variables available in body Stream msgbody = msgbody.Replace("{Name}", Model.Name); msgbody = msgbody.Replace("{Email}", Model.Email); msgbody = msgbody.Replace("{PhoneNo}", Model.PhoneNo); msgbody = msgbody.Replace("{Subject}", Model.Subject); msgbody = msgbody.Replace("{DescribeYourIssue}", Model.DescribeYourIssue); } mail.BodyEncoding = System.Text.Encoding.UTF8; mail.SubjectEncoding = System.Text.Encoding.UTF8; System.Net.Mail.AlternateView plainView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(System.Text.RegularExpressions.Regex.Replace(msgbody, @"<(.|\n)*?>", string.Empty), null, "text/plain"); System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(msgbody, null, "text/html"); mail.AlternateViews.Add(plainView); mail.AlternateViews.Add(htmlView); mail.IsBodyHtml = true; client.Send(mail); ModelState.Clear(); ViewBag.Message = "Thank you for Contacting us "; } catch (Exception ex) { ModelState.Clear(); ViewBag.Message = $" Sorry we are facing Problem here {ex.Message}"; } } return(View()); }
private void SetContent(bool allowUnicode) { //the attachments may have changed, so we need to reset the message if (_bodyView != null) { _bodyView.Dispose(); _bodyView = null; } if (AlternateViews.Count == 0 && Attachments.Count == 0) { if (!string.IsNullOrEmpty(_body)) { _bodyView = AlternateView.CreateAlternateViewFromString(_body, _bodyEncoding, (_isBodyHtml ? MediaTypeNames.Text.Html : null)); _message.Content = _bodyView.MimePart; } } else if (AlternateViews.Count == 0 && Attachments.Count > 0) { MimeMultiPart part = new MimeMultiPart(MimeMultiPartType.Mixed); if (!string.IsNullOrEmpty(_body)) { _bodyView = AlternateView.CreateAlternateViewFromString(_body, _bodyEncoding, (_isBodyHtml ? MediaTypeNames.Text.Html : null)); } else { _bodyView = AlternateView.CreateAlternateViewFromString(string.Empty); } part.Parts.Add(_bodyView.MimePart); foreach (Attachment attachment in Attachments) { if (attachment != null) { //ensure we can read from the stream. attachment.PrepareForSending(allowUnicode); part.Parts.Add(attachment.MimePart); } } _message.Content = part; } else { // we should not unnecessarily use Multipart/Mixed // When there is no attachement and all the alternative views are of "Alternative" types. MimeMultiPart part = null; MimeMultiPart viewsPart = new MimeMultiPart(MimeMultiPartType.Alternative); if (!string.IsNullOrEmpty(_body)) { _bodyView = AlternateView.CreateAlternateViewFromString(_body, _bodyEncoding, null); viewsPart.Parts.Add(_bodyView.MimePart); } foreach (AlternateView view in AlternateViews) { //ensure we can read from the stream. if (view != null) { view.PrepareForSending(allowUnicode); if (view.LinkedResources.Count > 0) { MimeMultiPart wholeView = new MimeMultiPart(MimeMultiPartType.Related); wholeView.ContentType.Parameters["type"] = view.ContentType.MediaType; wholeView.ContentLocation = view.MimePart.ContentLocation; wholeView.Parts.Add(view.MimePart); foreach (LinkedResource resource in view.LinkedResources) { //ensure we can read from the stream. resource.PrepareForSending(allowUnicode); wholeView.Parts.Add(resource.MimePart); } viewsPart.Parts.Add(wholeView); } else { viewsPart.Parts.Add(view.MimePart); } } } if (Attachments.Count > 0) { part = new MimeMultiPart(MimeMultiPartType.Mixed); part.Parts.Add(viewsPart); MimeMultiPart attachmentsPart = new MimeMultiPart(MimeMultiPartType.Mixed); foreach (Attachment attachment in Attachments) { if (attachment != null) { //ensure we can read from the stream. attachment.PrepareForSending(allowUnicode); attachmentsPart.Parts.Add(attachment.MimePart); } } part.Parts.Add(attachmentsPart); _message.Content = part; } // If there is no Attachement, AND only "1" Alternate View AND !!no body!! // then in fact, this is NOT a multipart region. else if (viewsPart.Parts.Count == 1 && string.IsNullOrEmpty(_body)) { _message.Content = viewsPart.Parts[0]; } else { _message.Content = viewsPart; } } if (_bodyView != null && _bodyTransferEncoding != TransferEncoding.Unknown) { _bodyView.TransferEncoding = _bodyTransferEncoding; } }
/// <summary> /// Adds a single LinkedResource to a mailPart /// </summary> public virtual LinkedResource PopulateLinkedResource(AlternateView mailPart, string contentId, string fileName) { var linkedResource = LinkedResourceProvider.Get(contentId, fileName); mailPart.LinkedResources.Add(linkedResource); return linkedResource; }
public static AlternateView CreateAlternateViewFromString (string content) { if (content == null) throw new ArgumentNullException (); MemoryStream ms = new MemoryStream (Encoding.UTF8.GetBytes (content)); AlternateView av = new AlternateView (ms); av.TransferEncoding = TransferEncoding.QuotedPrintable; return av; }
private void SendGroupMail(string mailid, string name) { try { DataTable dtRecord = new DataTable(); string body = null; SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]); string mailfrom = ConfigurationManager.AppSettings["mailfrom"]; string mailServer = ConfigurationManager.AppSettings["mailServer"]; string username = ConfigurationManager.AppSettings["UserName"]; string Password = ConfigurationManager.AppSettings["Password"]; string Port = ConfigurationManager.AppSettings["Port"]; string MailURL = ConfigurationManager.AppSettings["MailURL"]; string MailSSL = ConfigurationManager.AppSettings["MailSSL"]; string DisplayName = ConfigurationManager.AppSettings["DisplayName"]; string MailTo = mailid; string Mailbody = ""; dtRecord.Clear(); objdoreg.UserName = mailid; dtRecord = objdareg.GetDataTableRecord(objdoreg, DA_Registrationdetails.RegistrationDetails.UserRecordByMail); NetworkCredential cre = new NetworkCredential(username, Password); DataSet ds1 = new DataSet(); ds1 = (DataSet)ViewState["GetGroupDetailsByGroupId"]; SmtpClient clientip = new SmtpClient(mailServer); clientip.Port = Convert.ToInt32(Port); clientip.UseDefaultCredentials = true; clientip.Credentials = cre; if (MailSSL != "0") { clientip.EnableSsl = true; } string MailUrlFinal = MailURL + "/groups-members.aspx?GrpId=" + ds1.Tables[0].Rows[0]["inGroupId"]; try { MailMessage Rmm2 = new MailMessage(); Rmm2.IsBodyHtml = true; Rmm2.From = new System.Net.Mail.MailAddress(mailfrom, DisplayName); Rmm2.Body = Mailbody.ToString(); System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(""); if (Convert.ToString(ds1.Tables[0].Rows[0]["strAccess"]) == "A") { //htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString("<b>Skorkel group joining</b>" // + "<br><br>" + "Dear " + name + "<br><br> " // + "Your " + Convert.ToString(ds1.Tables[0].Rows[0]["strGroupName"]) + " group has been joined by " + Session["LoginName"] + "<br><br>" + "Regards," + "<br>" // + "Skorkel Team" + "<br><br>****This is a system generated Email. Kindly do not reply****", null, "text/html"); using (StreamReader reader = new StreamReader(Server.MapPath("~/EmailTemplate.htm"))) { body = reader.ReadToEnd(); } body = body.Replace("{UserName}", name); //body = body.Replace("{Content}", ViewState["LoginName"] + // " added you to the " + Convert.ToString(ds1.Tables[0].Rows[0]["strGroupName"]) + " group. <br>"); body = body.Replace("{Content}", "Your <b>" + Convert.ToString(ds1.Tables[0].Rows[0]["strGroupName"]) + "</b> group has been joined by <b>" + Session["LoginName"] + "</b>.<br>" + "Please click below to view group details: " + "<br><br><a href = '" + MailUrlFinal + "' style='background:#01B7BD;padding:5px 10px;border-radius:15px;color:#fff;text-decoration: none;'>View Details</a>"); body = body.Replace("{RedirectURL}", MailURL); htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html); Rmm2.To.Clear(); Rmm2.To.Add(MailTo); //Rmm2.Subject = "Skorkel group joining."; Rmm2.Subject = "Skorkel group joining " + Convert.ToString(ds1.Tables[0].Rows[0]["strGroupName"]) + " - " + Session["LoginName"]; FCMNotification.Send("Skorkel group joining " + Convert.ToString(ds1.Tables[0].Rows[0]["strGroupName"]) + " - " + Session["LoginName"], "Your " + Convert.ToString(ds1.Tables[0].Rows[0]["strGroupName"]) + " group has been joined by " + Session["LoginName"] + ".", Convert.ToString(dtRecord.Rows[0]["intRegistrationId"]), MailUrlFinal); } else if (Convert.ToString(ds1.Tables[0].Rows[0]["strAccess"]) == "R") { using (StreamReader reader = new StreamReader(Server.MapPath("~/EmailTemplate.htm"))) { body = reader.ReadToEnd(); } body = body.Replace("{UserName}", name); body = body.Replace("{Content} ", "<span style='font-weight:bold;font-size:14px;color:#373A36;'>" + Session["LoginName"] + "</span> wants to join <span style='font-weight:bold;font-size:14px;color:#373A36;'>" + Convert.ToString(ds1.Tables[0].Rows[0]["strGroupName"]) + "</span>" + "<br><br><a href='" + MailUrlFinal + "' style ='background: #01B7BD;padding: 5px 10px; border-radius: 15px;color: #fff;text-decoration: none;'>Accept</a>"); body = body.Replace("{RedirectURL}", MailURL); htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html); //htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString("<b>Skorkel group joining invitation</b>" + "<br><br>" + " " + name + " " + "You have a Skorkel group joining request posted by " + Session["LoginName"] + "<br><br><br>" + "Thanks," + "<br>" + "The Skorkel Team", null, "text/html"); Convert.ToString(ds1.Tables[0].Rows[0]["strGroupName"]); //htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString("<b>Skorkel Group Joining Request</b>" + "<br><br>" + "Dear " // + name + " <br><br>" // + Session["LoginName"] + " request you to allow joining " // + Convert.ToString(ds1.Tables[0].Rows[0]["strGroupName"]) + " group.<br><br>" // + "Regards," + "<br>" + "Skorkel Team" // + "<br><br>****This is a system generated Email. Kindly do not reply****", null, "text/html"); //Member_Name request you to allow joining 'Group_name' group Rmm2.To.Clear(); Rmm2.To.Add(MailTo); //Rmm2.Subject = "Skorkel Group Joining Request."; Rmm2.Subject = "Request to Join " + Convert.ToString(ds1.Tables[0].Rows[0]["strGroupName"]) + " - " + Session["LoginName"]; FCMNotification.Send("Request to Join " + Convert.ToString(ds1.Tables[0].Rows[0]["strGroupName"]) + " - " + Session["LoginName"], Session["LoginName"] + " wants to join " + Convert.ToString(ds1.Tables[0].Rows[0]["strGroupName"]), Convert.ToString(dtRecord.Rows[0]["intRegistrationId"]), MailUrlFinal); } else if (RequestType == "Send UnJoin request") { htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString("<b>Skorkel group unjoining invitation</b>" + "<br><br>" + " " + name + " " + "Your group has been unjoined by " + Session["LoginName"] + "<br><br><br>" + "Thanks," + "<br>" + "The Skorkel Team", null, "text/html"); Rmm2.To.Clear(); Rmm2.To.Add(MailTo); Rmm2.Subject = "Skorkel group unjoining notification"; } Rmm2.AlternateViews.Add(htmlView); Rmm2.IsBodyHtml = true; clientip.Send(Rmm2); Rmm2.To.Clear(); } catch (FormatException ex) { ex.Message.ToString(); return; } catch (SmtpException ex) { ex.Message.ToString(); return; } finally { conn.Close(); } } catch (Exception ex) { ex.Message.ToString(); } }
public string SendEmail(PersonModel model) { var subject = ""; if (model.Brokerage != "" && model.Brokerage != null && (model.Image == "" && model.Image == null)) { subject = "Niagra Fall Offer"; } else if (model.Image != "" && model.Image != null) { subject = "New Testimonial send by Client."; } else { subject = "Client contact mail."; } var EmailId = "*****@*****.**";// "*****@*****.**"; var Status = ""; try { //Send mail MailMessage mail = new MailMessage(); string FromEmailID = WebConfigurationManager.AppSettings["FromEmailID"]; string FromEmailPassword = WebConfigurationManager.AppSettings["FromEmailPassword"]; SmtpClient smtpClient = new SmtpClient(ConfigurationManager.AppSettings["SmtpServer"]); int _Port = Convert.ToInt32(WebConfigurationManager.AppSettings["Port"].ToString()); Boolean _UseDefaultCredentials = Convert.ToBoolean(WebConfigurationManager.AppSettings["UseDefaultCredentials"].ToString()); Boolean _EnableSsl = Convert.ToBoolean(WebConfigurationManager.AppSettings["EnableSsl"].ToString()); mail.To.Add(new MailAddress(EmailId)); mail.From = new MailAddress(FromEmailID); mail.Subject = subject; string msgbody = ""; msgbody += "<b>Name</b> : " + model.FirstName + "<br>"; msgbody += "<b>Email</b> : " + model.Email + "<br>"; msgbody += "<b>Phone No</b>: " + model.PhoneNo + "<br>"; if (model.Brokerage != "" && model.Brokerage != null && (model.Image == null && model.Image == "")) { msgbody += "<b>Brokerage</b> : " + model.Brokerage + "<br>"; } else if (model.Image != "" && model.Image != null) { msgbody += "<b>Brokerage</b> : " + model.Brokerage + "<br>"; msgbody += "<b>Description</b> : " + model.Remarks + "<br>"; msgbody += "<b>ImagePath</b> : " + model.Image + "<br>"; } else { msgbody += "<b>Comments</b> : " + model.Remarks + "<br>"; } mail.BodyEncoding = System.Text.Encoding.UTF8; mail.SubjectEncoding = System.Text.Encoding.UTF8; System.Net.Mail.AlternateView plainView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(System.Text.RegularExpressions.Regex.Replace(msgbody, @"<(.|\n)*?>", string.Empty), null, "text/plain"); System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(msgbody, null, "text/html"); mail.AlternateViews.Add(plainView); mail.AlternateViews.Add(htmlView); // mail.Body = msgbody; mail.IsBodyHtml = true; SmtpClient smtp = new SmtpClient(); smtp.DeliveryMethod = SmtpDeliveryMethod.Network; smtp.Host = "smtp.gmail.com"; //_Host; smtp.Port = _Port; //smtp.UseDefaultCredentials = _UseDefaultCredentials; smtp.Credentials = new System.Net.NetworkCredential(FromEmailID, FromEmailPassword); // Enter senders User name and password smtp.EnableSsl = _EnableSsl; smtp.Send(mail); Status = "success"; } catch { Status = "fail"; } return(Status); }
public static AlternateView CreateAlternateViewFromString (string content, ContentType contentType) { if (content == null) throw new ArgumentNullException ("content"); Encoding enc = contentType.CharSet != null ? Encoding.GetEncoding (contentType.CharSet) : Encoding.UTF8; MemoryStream ms = new MemoryStream (enc.GetBytes (content)); AlternateView av = new AlternateView (ms, contentType); av.TransferEncoding = TransferEncoding.QuotedPrintable; return av; }
/// <summary> /// Creates the alternate view. /// </summary> /// <param name="view">The view.</param> /// <returns></returns> private AlternateView CreateAlternateView(MimeEntity view) { AlternateView alternateView = new AlternateView(view.Content, view.ContentType); alternateView.TransferEncoding = view.ContentTransferEncoding; alternateView.ContentId = TrimBrackets(view.ContentId); return alternateView; }
private void SendBodylessSingleAlternate (AlternateView av) { SendHeader (HeaderName.ContentType, av.ContentType.ToString ()); if (av.TransferEncoding != TransferEncoding.SevenBit) SendHeader (HeaderName.ContentTransferEncoding, GetTransferEncodingName (av.TransferEncoding)); SendData (string.Empty); SendData (EncodeBody (av)); }
public static bool SendNewsLetter(string Email, string Path) { //Email = "*****@*****.**"; //Send mail bool status = false; MailMessage mail = new MailMessage(); var FirstImg = ""; var SecondImg = ""; if (Path.IndexOf(',') > -1) { var splitedpath = Path.Split(','); FirstImg = splitedpath[0].ToString(); SecondImg = splitedpath[1].ToString(); } else { FirstImg = Path; } try { string FromEmailID = ""; string FromEmailPassword = ""; if (EMailAddress != "" && EmailPassword != "") { FromEmailID = EMailAddress; FromEmailPassword = EmailPassword; } else { FromEmailID = ConfigurationManager.AppSettings["FromEmailID"]; FromEmailPassword = ConfigurationManager.AppSettings["FromEmailPassword"]; } if (FromEmailID == "*****@*****.**") { SmtpClient smtpClient = new SmtpClient(ConfigurationManager.AppSettings["SmtpServer1and1"]); } else { SmtpClient smtpClient = new SmtpClient(ConfigurationManager.AppSettings["SmtpServer"]); } int _Port = Convert.ToInt32(ConfigurationManager.AppSettings["Port"].ToString()); Boolean _UseDefaultCredentials = Convert.ToBoolean(ConfigurationManager.AppSettings["UseDefaultCredentials"].ToString()); Boolean _EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"].ToString()); mail.To.Add(new MailAddress(Email)); mail.From = new MailAddress(FromEmailID); mail.Subject = "Greetings"; string msgbody = ""; if (dbname == "Parag_Tandon_conn" || dbname == "Vipan_Jassal_conn" || dbname == "AjayShah_conn" || dbname == "Rajiv_Bakshi_conn" || dbname == "Gunjan_Virk_conn" || dbname == "Jay_Singh_conn" || dbname == "Gurmail_Kamboj_conn" || dbname == "Shallu_Sharma_conn" || dbname == "Sheikh_Kashif_conn" || dbname == "Seeya_Shah_conn" || dbname == "Sudesh_conn" || dbname == "Manjit_Kundhal_conn" || dbname == "Dalip_conn" || dbname == "Satish_Patil_conn" || dbname == "Rajguru_conn" || dbname == "Mitesh_conn" || dbname == "Bobby_conn" || dbname == "Raja_conn" || dbname == "Khalid_Ahmed_conn" || dbname == "Pankaj_conn" || dbname == "TeamSinghKaur_conn" || dbname == "Team_Sidhu_conn" || dbname == "Dev_conn" || dbname == "Harvinder_Sohi_conn" || dbname == "Charanjit_conn" || dbname == "Nikita_conn" || dbname == "Fara_conn" || dbname == "SatishSharma_conn" || dbname == "Rashpal_conn" || dbname == "Suchi_conn" || dbname == "Suresh_conn" || dbname == "Rohit_conn" || dbname == "Varinder_conn" || dbname == "Ranbir_conn" || dbname == "Condo_conn" || dbname == "Sanjiv_conn" || dbname == "Praba_conn" || dbname == "Hetal_conn" || dbname == "Shveta_conn") { string url = dbname + "_LiveURL"; FirstImg = ConfigurationManager.AppSettings[url].ToString() + "uploadfiles/" + FirstImg; SecondImg = ConfigurationManager.AppSettings[url].ToString() + "uploadfiles/" + SecondImg; } if (dbname == "Parag_Tandon_conn") { using (StreamReader reader = new StreamReader(@"C:\sites\RealEstate_NewsLetter\RealEstate_NewsLetter\Templates\SixNewLetter_withUnsub.html")) { msgbody = reader.ReadToEnd(); msgbody = msgbody.Replace("{FirstImg}", FirstImg); msgbody = msgbody.Replace("{SecondImg}", SecondImg); msgbody = msgbody.Replace("{EmailId}", Email); } } else { using (StreamReader reader = new StreamReader(@"C:\sites\RealEstate_NewsLetter\RealEstate_NewsLetter\Templates\SixNewLetter.html")) { msgbody = reader.ReadToEnd(); msgbody = msgbody.Replace("{FirstImg}", FirstImg); msgbody = msgbody.Replace("{SecondImg}", SecondImg); } } mail.BodyEncoding = System.Text.Encoding.UTF8; mail.SubjectEncoding = System.Text.Encoding.UTF8; System.Net.Mail.AlternateView plainView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(System.Text.RegularExpressions.Regex.Replace(msgbody, @"<(.|\n)*?>", string.Empty), null, "text/plain"); System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(msgbody, null, "text/html"); mail.AlternateViews.Add(plainView); mail.AlternateViews.Add(htmlView); // mail.Body = msgbody; mail.IsBodyHtml = true; SmtpClient smtp = new SmtpClient(); smtp.DeliveryMethod = SmtpDeliveryMethod.Network; smtp.Host = "smtp.gmail.com"; smtp.Port = _Port; smtp.Credentials = new System.Net.NetworkCredential(FromEmailID, FromEmailPassword);// Enter senders User name and password smtp.EnableSsl = _EnableSsl; smtp.Send(mail); status = true; System.Threading.Thread.Sleep(7000); } catch (Exception ex) { status = false; SqlConnection rajpal_conn = new SqlConnection(ConfigurationManager.ConnectionStrings["rajpal_conn"].ConnectionString.ToString()); SqlDataAdapter adapter = new SqlDataAdapter(); string sql = null; sql = "insert into errorlog ([DBname],[message],[EmailId]) values('" + dbname + "','" + ex.Message.ToString() + "in send mail function. (greetings)" + "','" + Email + "')"; try { rajpal_conn.Open(); adapter.InsertCommand = new SqlCommand(sql, rajpal_conn); adapter.InsertCommand.ExecuteNonQuery(); } catch (Exception ex1) { rajpal_conn.Close(); } } return(status); }
private string EncodeBody (AlternateView av) { //Encoding encoding = av.ContentType.CharSet != null ? Encoding.GetEncoding (av.ContentType.CharSet) : Encoding.UTF8; byte [] bytes = new byte [av.ContentStream.Length]; av.ContentStream.Read (bytes, 0, bytes.Length); // RFC 2045 encoding switch (av.TransferEncoding) { case TransferEncoding.SevenBit: return Encoding.ASCII.GetString (bytes); case TransferEncoding.Base64: return Convert.ToBase64String (bytes, Base64FormattingOptions.InsertLineBreaks); default: return ToQuotedPrintable (bytes); } }
/// <summary> /// Adds a new Alternate view to the request. Passed from FoxPro /// which sets up this object. /// </summary> /// <param name="text"></param> /// <param name="contentType"></param> /// <param name="contentId"></param> public void AddAlternateView(AlternateView view) { this.AlternateViews.Add(view); }
public static AlternateView CreateAlternateViewFromString(string content, ContentType contentType) { AlternateView view = new AlternateView(); view.SetContentFromString(content, contentType); return view; }
private void SetContent(bool allowUnicode) { //the attachments may have changed, so we need to reset the message if (_bodyView != null) { _bodyView.Dispose(); _bodyView = null; } if (AlternateViews.Count == 0 && Attachments.Count == 0) { if (!string.IsNullOrEmpty(_body)) { _bodyView = AlternateView.CreateAlternateViewFromString(_body, _bodyEncoding, (_isBodyHtml ? MediaTypeNames.Text.Html : null)); _message.Content = _bodyView.MimePart; } } else if (AlternateViews.Count == 0 && Attachments.Count > 0) { MimeMultiPart part = new MimeMultiPart(MimeMultiPartType.Mixed); if (!string.IsNullOrEmpty(_body)) { _bodyView = AlternateView.CreateAlternateViewFromString(_body, _bodyEncoding, (_isBodyHtml ? MediaTypeNames.Text.Html : null)); } else { _bodyView = AlternateView.CreateAlternateViewFromString(string.Empty); } part.Parts.Add(_bodyView.MimePart); foreach (Attachment attachment in Attachments) { if (attachment != null) { //ensure we can read from the stream. attachment.PrepareForSending(allowUnicode); part.Parts.Add(attachment.MimePart); } } _message.Content = part; } else { // we should not unnecessarily use Multipart/Mixed // When there is no attachement and all the alternative views are of "Alternative" types. MimeMultiPart?part = null; MimeMultiPart viewsPart = new MimeMultiPart(MimeMultiPartType.Alternative); if (!string.IsNullOrEmpty(_body)) { _bodyView = AlternateView.CreateAlternateViewFromString(_body, _bodyEncoding, null); viewsPart.Parts.Add(_bodyView.MimePart); } foreach (AlternateView view in AlternateViews) { //ensure we can read from the stream. if (view != null) { view.PrepareForSending(allowUnicode); if (view.LinkedResources.Count > 0) { MimeMultiPart wholeView = new MimeMultiPart(MimeMultiPartType.Related); wholeView.ContentType.Parameters["type"] = view.ContentType.MediaType; wholeView.ContentLocation = view.MimePart.ContentLocation; wholeView.Parts.Add(view.MimePart); foreach (LinkedResource resource in view.LinkedResources) { //ensure we can read from the stream. resource.PrepareForSending(allowUnicode); wholeView.Parts.Add(resource.MimePart); } viewsPart.Parts.Add(wholeView); } else { viewsPart.Parts.Add(view.MimePart); } } } if (Attachments.Count > 0) { part = new MimeMultiPart(MimeMultiPartType.Mixed); part.Parts.Add(viewsPart); MimeMultiPart attachmentsPart = new MimeMultiPart(MimeMultiPartType.Mixed); foreach (Attachment attachment in Attachments) { if (attachment != null) { //ensure we can read from the stream. attachment.PrepareForSending(allowUnicode); attachmentsPart.Parts.Add(attachment.MimePart); } } part.Parts.Add(attachmentsPart); _message.Content = part; } // If there is no Attachement, AND only "1" Alternate View AND !!no body!! // then in fact, this is NOT a multipart region. else if (viewsPart.Parts.Count == 1 && string.IsNullOrEmpty(_body)) { _message.Content = viewsPart.Parts[0]; } else { _message.Content = viewsPart; } } if (_bodyView != null && _bodyTransferEncoding != TransferEncoding.Unknown) { _bodyView.TransferEncoding = _bodyTransferEncoding; } }
/// <summary> /// Add all attachments and alternative views from child to the parent /// </summary> private void AddChildPartsToParent(RxMailMessage child, RxMailMessage parent) { //add the child itself to the parent parent.Entities.Add(child); //add the alternative views of the child to the parent if (child.AlternateViews!=null) { foreach (AlternateView childView in child.AlternateViews) { parent.AlternateViews.Add(childView); } } //add the body of the child as alternative view to parent //this should be the last view attached here, because the POP 3 MIME client //is supposed to display the last alternative view if (child.MediaMainType=="text" && child.ContentStream!=null && child.Parent.ContentType!=null && child.Parent.ContentType.MediaType.ToLowerInvariant()=="multipart/alternative") { AlternateView thisAlternateView = new AlternateView(child.ContentStream); thisAlternateView.ContentId = RemoveBrackets(child.ContentId); thisAlternateView.ContentType = child.ContentType; thisAlternateView.TransferEncoding = child.ContentTransferEncoding; parent.AlternateViews.Add(thisAlternateView); } //add the attachments of the child to the parent if (child.Attachments!=null) { foreach (Attachment childAttachment in child.Attachments) { parent.Attachments.Add(childAttachment); } } }
/// <summary> /// Add all attachments and alternative views from child to the parent /// </summary> /// <param name="child">child Object</param> /// <param name="parent">parent Object</param> private static void AddChildPartsToParent(MailMessageParser child, MailMessageParser parent) { ////add the child itself to the parent parent.Entities.Add(child); ////add the alternative views of the child to the parent if (null != child.AlternateViews) { foreach (AlternateView childView in child.AlternateViews) { parent.AlternateViews.Add(childView); } } ////add the body of the child as alternative view to parent ////this should be the last view attached here, because the POP 3 MIME client ////is supposed to display the last alternative view if (child.MediaMainType == ServiceConstants.TEXT_MEDIA_MAIN_TYPE && null != child.ContentStream && null != child.Parent.ContentType && child.Parent.ContentType.MediaType.ToUpperInvariant() == ServiceConstants.MULTI_PART_MEDIA_TYPE) { AlternateView thisAlternateView = new AlternateView(child.ContentStream); thisAlternateView.ContentId = RemoveBrackets(child.ContentId); thisAlternateView.ContentType = child.ContentType; thisAlternateView.TransferEncoding = child.ContentTransferEncoding; parent.AlternateViews.Add(thisAlternateView); } ////add the attachments of the child to the parent if (null != child.Attachments) { foreach (Attachment childAttachment in child.Attachments) { parent.Attachments.Add(childAttachment); } } }
/// <summary> /// This method will convert this <see cref="Message"/> into a <see cref="MailMessage"/> equivalent.<br/> /// The returned <see cref="MailMessage"/> can be used with <see cref="System.Net.Mail.SmtpClient"/> to forward the email.<br/> /// <br/> /// You should be aware of the following about this method: /// <list type="bullet"> /// <item> /// All sender and receiver mail addresses are set. /// If you send this email using a <see cref="System.Net.Mail.SmtpClient"/> then all /// receivers in To, From, Cc and Bcc will receive the email once again. /// </item> /// <item> /// If you view the source code of this Message and looks at the source code of the forwarded /// <see cref="MailMessage"/> returned by this method, you will notice that the source codes are not the same. /// The content that is presented by a mail client reading the forwarded <see cref="MailMessage"/> should be the /// same as the original, though. /// </item> /// <item> /// Content-Disposition headers will not be copied to the <see cref="MailMessage"/>. /// It is simply not possible to set these on Attachments. /// </item> /// <item> /// HTML content will be treated as the preferred view for the <see cref="MailMessage.Body"/>. Plain text content will be used for the /// <see cref="MailMessage.Body"/> when HTML is not available. /// </item> /// </list> /// </summary> /// <returns>A <see cref="MailMessage"/> object that contains the same information that this Message does</returns> public MailMessage ToMailMessage() { // Construct an empty MailMessage to which we will gradually build up to look like the current Message object (this) MailMessage message = new MailMessage(); message.Subject = Headers.Subject; // We here set the encoding to be UTF-8 // We cannot determine what the encoding of the subject was at this point. // But since we know that strings in .NET is stored in UTF, we can // use UTF-8 to decode the subject into bytes message.SubjectEncoding = Encoding.UTF8; // The HTML version should take precedent over the plain text if it is available MessagePart preferredVersion = FindFirstHtmlVersion(); if ( preferredVersion != null ) { // Make sure that the IsBodyHtml property is being set correctly for our content message.IsBodyHtml = true; } else { // otherwise use the first plain text version as the body, if it exists preferredVersion = FindFirstPlainTextVersion(); } if (preferredVersion != null) { message.Body = preferredVersion.GetBodyAsText(); message.BodyEncoding = preferredVersion.BodyEncoding; } // Add body and alternative views (html and such) to the message IEnumerable<MessagePart> textVersions = FindAllTextVersions(); foreach (MessagePart textVersion in textVersions) { // The textVersions also contain the preferred version, therefore // we should skip that one if (textVersion == preferredVersion) continue; MemoryStream stream = new MemoryStream(textVersion.Body); AlternateView alternative = new AlternateView(stream); alternative.ContentId = textVersion.ContentId; alternative.ContentType = textVersion.ContentType; message.AlternateViews.Add(alternative); } // Add attachments to the message IEnumerable<MessagePart> attachments = FindAllAttachments(); foreach (MessagePart attachmentMessagePart in attachments) { MemoryStream stream = new MemoryStream(attachmentMessagePart.Body); Attachment attachment = new Attachment(stream, attachmentMessagePart.ContentType); attachment.ContentId = attachmentMessagePart.ContentId; attachment.Name = String.IsNullOrEmpty(attachment.Name) ? attachmentMessagePart.FileName : attachment.Name; attachment.ContentDisposition.FileName = String.IsNullOrEmpty(attachment.ContentDisposition.FileName) ? attachmentMessagePart.FileName : attachment.ContentDisposition.FileName; message.Attachments.Add(attachment); } if(Headers.From != null && Headers.From.HasValidMailAddress) message.From = Headers.From.MailAddress; if (Headers.ReplyTo != null && Headers.ReplyTo.HasValidMailAddress) message.ReplyTo = Headers.ReplyTo.MailAddress; if(Headers.Sender != null && Headers.Sender.HasValidMailAddress) message.Sender = Headers.Sender.MailAddress; foreach (RfcMailAddress to in Headers.To) { if(to.HasValidMailAddress) message.To.Add(to.MailAddress); } foreach (RfcMailAddress cc in Headers.Cc) { if (cc.HasValidMailAddress) message.CC.Add(cc.MailAddress); } foreach (RfcMailAddress bcc in Headers.Bcc) { if (bcc.HasValidMailAddress) message.Bcc.Add(bcc.MailAddress); } return message; }
public string SendNewsLetter(PostCardModel model) { string Status = ""; string EmailId = "*****@*****.**"; //Send mail MailMessage mail = new MailMessage(); string FromEmailID = WebConfigurationManager.AppSettings["RegFromMailAddress"]; string FromEmailPassword = WebConfigurationManager.AppSettings["RegPassword"]; SmtpClient smtpClient = new SmtpClient(ConfigurationManager.AppSettings["SmtpServer"]); int _Port = Convert.ToInt32(WebConfigurationManager.AppSettings["Port"].ToString()); Boolean _UseDefaultCredentials = Convert.ToBoolean(WebConfigurationManager.AppSettings["UseDefaultCredentials"].ToString()); Boolean _EnableSsl = Convert.ToBoolean(WebConfigurationManager.AppSettings["EnableSsl"].ToString()); mail.To.Add(new MailAddress(model.Email)); mail.From = new MailAddress(FromEmailID); mail.Subject = "Post Card"; string Template = ""; string msgbody = ""; if (model.PostcardType == "Openhouse") { Template = "Templates/OpenHousePostCard.html"; } else if (model.PostcardType == "feature") { Template = "Templates/Feature_Postcard.html"; } else if (model.PostcardType == "2ndfeature") { Template = "Templates/2ndFeature_Postcard.html"; } else if (model.PostcardType == "jst_sold") { Template = "Templates/Jst_sold.html"; } // using (StreamReader reader = new StreamReader(HttpContext.Current.Server.MapPath(Template))) using (StreamReader reader = new StreamReader(Path.Combine(HttpRuntime.AppDomainAppPath, Template))) { msgbody = reader.ReadToEnd(); //Replace UserName and Other variables available in body Stream msgbody = msgbody.Replace("{PropertyPhoto}", model.PropertyPhoto); if (model.PostcardType == "Openhouse") { msgbody = Replace_openhouse(model, msgbody); } else if (model.PostcardType == "feature") { msgbody = Replace_first_ftr(model, msgbody); } else if (model.PostcardType == "2ndfeature") { msgbody = Replace_second_ftr(model, msgbody); } else if (model.PostcardType == "jst_sold") { msgbody = Replace_JustSold(model, msgbody); } } mail.BodyEncoding = System.Text.Encoding.UTF8; mail.SubjectEncoding = System.Text.Encoding.UTF8; System.Net.Mail.AlternateView plainView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(System.Text.RegularExpressions.Regex.Replace(msgbody, @"<(.|\n)*?>", string.Empty), null, "text/plain"); System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(msgbody, null, "text/html"); mail.AlternateViews.Add(plainView); mail.AlternateViews.Add(htmlView); // mail.Body = msgbody; mail.IsBodyHtml = true; SmtpClient smtp = new SmtpClient(); smtp.DeliveryMethod = SmtpDeliveryMethod.Network; smtp.Host = "smtp.gmail.com"; //_Host; smtp.Port = _Port; //smtp.UseDefaultCredentials = _UseDefaultCredentials; smtp.Credentials = new System.Net.NetworkCredential(FromEmailID, FromEmailPassword); // Enter senders User name and password smtp.EnableSsl = _EnableSsl; smtp.Send(mail); return(Status); }
public void GetReady () { avc = new MailMessage ("*****@*****.**", "*****@*****.**").AlternateViews; av = AlternateView.CreateAlternateViewFromString ("test", new ContentType ("text/plain")); }
/// <summary> /// Public static method to send email out using the .NET MailMessage object and SMTP service /// </summary> /// <param name="mailSubject">Subject of the mail</param> /// <param name="textBody">Body of the mail</param> /// <param name="mailTo">Address the email is being sent to</param> /// <param name="messageEncoding">Encoding to be applied to the email body</param> public static void SendEmail(string mailSubject, string textBody, string mailTo, Encoding messageEncoding) { try { MemoryStream textStream = new MemoryStream(); AlternateView textView = null; if (!string.IsNullOrEmpty(textBody)) { textStream = new MemoryStream(Encoding.ASCII.GetBytes(textBody)); textView = new AlternateView(MediaTypeNames.Text.Plain); } MailMessage message = new MailMessage(); message.From = new MailAddress(ConfigurationManager.AppSettings["EmailFrom"]); message.To.Add(new MailAddress(mailTo)); message.Subject = mailSubject; message.BodyEncoding = messageEncoding; if (textView != null) message.AlternateViews.Add(textView); SmtpClient client = new SmtpClient(); client.Send(message); } catch (Exception ex) { EventLog.WriteEntry("FilesTidy", string.Format("Email failed to send for the following reason {0}", ex.Message), EventLogEntryType.Warning); } finally { EventLog.WriteEntry("FilesTidy", string.Format("Email sent to {0}", mailTo), EventLogEntryType.Information); } }