//Configuración esta en Web.config public static EEmailStatus EnviarEmail( EEmail Emisor, List <EEmail> Destinatarios, string Asunto, string Cuerpo, List <EEmail> CC = null, List <EEmail> CCO = null, List <Attachment> Adjuntos = null, bool FormatoHtml = true) { try { using (MailMessage sms = new MailMessage()) { //Dirección que envia el correo sms.From = new MailAddress(Emisor.Email, Emisor.Nombre); //Destinatarios foreach (EEmail obj in Destinatarios) { if (obj.Email != null && obj.Email != "") { sms.To.Add(new MailAddress(obj.Email, obj.Nombre)); } } //CC (Con Copia) if (CC != null) { foreach (EEmail obj in CC) { if (obj.Email != null && obj.Email != "") { sms.CC.Add(new MailAddress(obj.Email, obj.Nombre)); } } } //CCO (Con Copia oculta) if (CCO != null) { foreach (EEmail obj in CCO) { if (obj.Email != null && obj.Email != "") { sms.Bcc.Add(new MailAddress(obj.Email, obj.Nombre)); } } } //Asunto del correo sms.Subject = Asunto == null ? "" : Asunto.Replace("\n", " ").Replace("\r", " "); //Cuerpo o contenido del correo if (FormatoHtml) { AlternateView avHtml = AlternateView.CreateAlternateViewFromString(Cuerpo, System.Text.Encoding.UTF8, System.Net.Mime.MediaTypeNames.Text.Html); sms.AlternateViews.Add(avHtml); } else { sms.Body = Cuerpo; //sms.IsBodyHtml = true; } if (Adjuntos != null) { foreach (Attachment archivo in Adjuntos) { sms.Attachments.Add(archivo); } } sms.Priority = MailPriority.Normal; using (SmtpClient smtp = new SmtpClient()) { smtp.Send(sms); } return(new EEmailStatus { Estado = true, Mensaje = "Se ha enviado el correo a los destinatarios" }); } } catch (Exception ex) { return(new EEmailStatus { Estado = false, Mensaje = "No se pudo enviar el correo a los destinatarios", ErrorTecnico = ex.Message }); } }
public async Task <bool> SendAsync(EmailType type, IEnumerable <string> to, IEnumerable <string> cc, string subject, string content) { var emailInformation = EmailHelper.ToEmailItems(Settings, type, to, cc, subject, content); var msg = new MailMessage { From = new MailAddress(emailInformation.FromEmail, emailInformation.FromName), Subject = emailInformation.Subject }; foreach (var email in emailInformation.To) { msg.To.Add(new MailAddress(email)); } foreach (var email in emailInformation.Cc) { msg.CC.Add(new MailAddress(email)); } foreach (var email in emailInformation.Bcc) { msg.Bcc.Add(new MailAddress(email)); } msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(emailInformation.Body, null, MediaTypeNames.Text.Plain)); msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(emailInformation.Body.ToHtml(), null, MediaTypeNames.Text.Html)); using var client = new SmtpClient { DeliveryMethod = SmtpDeliveryMethod.Network, EnableSsl = DotNetSettings.EnableSsl }; var host = DotNetSettings.Host; if (!string.IsNullOrWhiteSpace(host)) { client.Host = host; } var port = DotNetSettings.Port; if (port.HasValue && port.Value != 0) { client.Port = port.Value; } var password = DotNetSettings.Password; if (!string.IsNullOrWhiteSpace(password)) { client.UseDefaultCredentials = false; var decrypted = password.Decrypt(Encryption).Value; client.Credentials = new NetworkCredential(emailInformation.FromEmail, decrypted); } // Must leave as try/catch because the client would otherwise be disposed and not captured try { await client.SendMailAsync(msg); return(true); } #pragma warning disable 168 catch (Exception ex) #pragma warning restore 168 { return(false); } }
// Method for doing the e-mailing action. Assumes a single template set in the main class public void EmailFileFromTemplate(string fromAddress, string[] toAddresses, string[] ccAddresses, string[] bccAddresses, string subject, string simpleMessageText, string filenameToAttach) { this.Log("Actually sending from " + fromAddress); string MessageText = ""; // Load Text template file. If it doesn't exist, just use the simple message text if (this.TextEmailTemplateFilename != "") { try { using (StreamReader sr = new StreamReader(this.TextEmailTemplateFilename)) { MessageText = sr.ReadToEnd(); } } catch (Exception e) { Console.WriteLine(e.Message); } } else { MessageText = simpleMessageText; } // Initiate the mail message MailMessage Message = new MailMessage() { From = new MailAddress(fromAddress), Body = MessageText, Subject = subject }; this.Log("Message created effectively"); // Run through the string arrays of e-mail addresses and add them to the necessary SMTP collections foreach (var toUser in toAddresses) { if (!String.IsNullOrEmpty(toUser)) { Message.To.Add(new MailAddress(toUser)); } } foreach (var ccUser in ccAddresses) { if (!String.IsNullOrEmpty(ccUser)) { Message.CC.Add(new MailAddress(ccUser)); } ; } foreach (var bccUser in bccAddresses) { if (!String.IsNullOrEmpty(bccUser)) { Message.Bcc.Add(new MailAddress(bccUser)); } } this.Log("Added all the addresses"); // Load HTML template as alternative message type if (this.HtmlEmailTemplateFilename != "") { try { using (StreamReader sr = new StreamReader(this.HtmlEmailTemplateFilename)) { ContentType mimeType = new System.Net.Mime.ContentType("text/html"); AlternateView htmlAltView = AlternateView.CreateAlternateViewFromString(sr.ReadToEnd(), mimeType); Message.AlternateViews.Add(htmlAltView); } } catch (Exception e) { Console.WriteLine(e.Message); } } // Add the attachment Attachment att = new Attachment(filenameToAttach); Message.Attachments.Add(att); // Send the message via the SmtpServer object this.SmtpServer.Send(Message); // Must close the attachment or file will stay locked to the program and you can't clean up att.Dispose(); }
public static string SendaMail() { var ToAddress = ConfigurationManager.AppSettings["EmailTo"].ToString(); var CcAddress = ""; var MailSubject = ConfigurationManager.AppSettings["MailSubject"].ToString(); var MailBody = "Account has been created Successfully"; var IsBodyHtml = true; var FileAttach = ""; SmtpClient obj = new SmtpClient(); MailMessage msg = new MailMessage(); string Result = ""; //string stastus = ConfigurationManager.AppSettings["IsLive"]; if (ConfigurationManager.AppSettings["IsLive"] == "Y") { } else { // For Test ToAddress = ConfigurationManager.AppSettings["EmailTo"]; } try { //string DisplayName = "PEP List and BlackList"; string DisplayName = ConfigurationManager.AppSettings["DisplayName"].ToString(); MailAddress FromAddress = new MailAddress(ConfigurationManager.AppSettings["EmailFrom"], DisplayName); msg.From = FromAddress; string[] temp = null; if (string.IsNullOrEmpty(ToAddress)) { } else { temp = ToAddress.Split(new Char[] { ',' }); foreach (string s in temp) { if (ValidateEmail(s)) { msg.To.Add(s); } } // msg.To.Add(ToAddress) } if (string.IsNullOrEmpty(CcAddress)) { } else { temp = CcAddress.Trim().Split(new Char[] { ',' }); foreach (string s in temp) { if (ValidateEmail(s)) { msg.Bcc.Add(s); } } // msg.CC.Add(CcAddress) } msg.Subject = MailSubject; if (string.IsNullOrEmpty(FileAttach)) { } else { Attachment attachment; attachment = new System.Net.Mail.Attachment(FileAttach); msg.Attachments.Add(attachment); //msg.Attachments.Add(new Attachment("")); } //string StartupPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); dynamic emailServer = ConfigurationManager.AppSettings["EmailServer"]; string path = "\\EmailPage.html"; string rootPath = Directory.GetCurrentDirectory(); var stringPath = rootPath + path; StreamReader str = new StreamReader(stringPath); string MailText = str.ReadToEnd(); str.Close(); AlternateView plainView = AlternateView.CreateAlternateViewFromString(MailText, null, "text/html"); var fileName = stringPath; if (IsBodyHtml == true) { msg.AlternateViews.Add(plainView); } msg.IsBodyHtml = IsBodyHtml; msg.Body = MailBody; obj.Host = emailServer; obj.Send(msg); Result = "Sent"; //Log4Net.Log.Info("Sent"); } catch (Exception ex) { //Log4Net.Log.Error("Error: ", ex); Result = ex.Message; // nloger.Log(LogLevel.Info, "SendMail Error: " + ex.Message); // ex.Log() } finally { msg.Dispose(); } return(Result); }
public ActionResult ErrorCorrection([DataSourceRequest] DataSourceRequest request, Logger us, FormCollection colletion) { if (ModelState.IsValid) { string to_name = "", to_email = "", logger_sites_name = "", zone_name = "" , logger_sms = "", company_name = ""; using (var db = new poseidon_dbEntities()) { string myCheckBoxValue = Request.Form["Check"].ToString(); string[] selectedList = myCheckBoxValue.Split(','); Boolean error_value = Convert.ToBoolean(selectedList[0]); if (error_value == true) { var result = from u in db.Logger where (u.logger_id == us.logger_id) select u; if (result.Count() != 0) { var dblogger = result.First(); dblogger.status = 1; db.SaveChanges(); logger_sites_name = dblogger.logger_sites_name; zone_name = dblogger.zone_name; logger_sms = dblogger.logger_sms.ToString(); var company_from = from u in db.Company where (u.company_id == dblogger.company_id) select u; company_name = company_from.First().company_name; var user_from = from u in db.Customers where (u.customer_company_id == dblogger.company_id && u.cc.HasValue == true) select u; var detail_user_from = user_from.First(); to_name = "Jonathan"; //detail_user_from.customer_name; to_email = "*****@*****.**"; // detail_user_from.customer_email; } } } MailMessage mail = new MailMessage(); mail.From = new MailAddress("*****@*****.**", "Instalaciones", System.Text.Encoding.UTF8); mail.Subject = "Notificación Corrección de problema - " + company_name;//titulo mail.SubjectEncoding = System.Text.Encoding.UTF8; string body = ""; body = @"<p><h3>Estimado(a) " + to_name + ",</h3><p>" + "<p></p><p>Se ha generado el siguiente email para notificar que el problema de instalación detectado se ha solucionado:" + "<p>Ubicación:" + logger_sites_name + "<p>Localidad:" + logger_sites_name + "<p>Región:" + zone_name + "<p>SMS:" + logger_sms; AlternateView htmlView = AlternateView.CreateAlternateViewFromString(body, new ContentType("text/html")); mail.AlternateViews.Add(htmlView); mail.To.Add(to_email); mail.CC.Add("*****@*****.**"); mail.Priority = MailPriority.High; SmtpClient smtp = new SmtpClient(); smtp.Credentials = new System.Net.NetworkCredential("*****@*****.**", "dnkinstalaciones2015"); smtp.Port = 587;//puerto smtp.Host = "smtp.gmail.com"; smtp.EnableSsl = true; smtp.Send(mail); } return(RedirectToAction("ListLogger", "UserLogger")); }
public string SendSmtpMsg(MailAddress fromAddress, string subject, string message, List <MailAddress> to, int?id, int?pid, List <LinkedResource> attachments = null, List <MailAddress> cc = null) { var senderrorsto = ConfigurationManager.AppSettings["senderrorsto"]; var msg = new MailMessage(); if (fromAddress == null) { fromAddress = Util.FirstAddress(senderrorsto); } var fromDomain = DefaultFromDomain; msg.From = new MailAddress(fromDomain, fromAddress.DisplayName); msg.ReplyToList.Add(fromAddress); if (cc != null) { foreach (var a in cc) { msg.ReplyToList.Add(a); } if (!msg.ReplyToList.Contains(msg.From) && msg.From.Address.NotEqual(fromDomain)) { msg.ReplyToList.Add(msg.From); } } msg.Headers.Add(XSmtpApi, XSmtpApiHeader(id, pid, fromDomain)); msg.Headers.Add(XBvcms, XBvcmsHeader(id, pid)); foreach (var ma in to) { if (ma.Host != "nowhere.name" || Util.IsInRoleEmailTest) { msg.AddAddr(ma); } } msg.Subject = subject; var badEmailLink = ""; if (msg.To.Count == 0 && to.Any(tt => tt.Host == "nowhere.name")) { return(null); } if (msg.To.Count == 0) { msg.AddAddr(msg.From); msg.AddAddr(Util.FirstAddress(senderrorsto)); msg.Subject += $"-- bad addr for {CmsHost}({pid})"; badEmailLink = $"<p><a href='{CmsHost}/Person2/{pid}'>bad addr for</a></p>\n"; } var regex = new Regex("</?([^>]*)>", RegexOptions.IgnoreCase | RegexOptions.Multiline); var text = regex.Replace(message, string.Empty); var textview = AlternateView.CreateAlternateViewFromString(text, Encoding.UTF8, MediaTypeNames.Text.Plain); textview.TransferEncoding = TransferEncoding.Base64; msg.AlternateViews.Add(textview); var html = badEmailLink + message + CcMessage(cc); using (var htmlView = AlternateView.CreateAlternateViewFromString(html, Encoding.UTF8, MediaTypeNames.Text.Html)) { htmlView.TransferEncoding = TransferEncoding.Base64; if (attachments != null) { foreach (var a in attachments) { htmlView.LinkedResources.Add(a); } } msg.AlternateViews.Add(htmlView); var smtp = Smtp(); smtp.Send(msg); } return(fromDomain); }
public void CreateAlternateViewFromStringEncodingNull() { AlternateView av = AlternateView.CreateAlternateViewFromString("<p>test message</p>", null, "text/html"); Assert.Equal(Text.Encoding.ASCII.BodyName, av.ContentType.CharSet); }
public static bool SendCustomerDetailsToCustomer(Customer c, Branch b) { Cursor.Current = Cursors.WaitCursor; //QR Code Generation and Content Stream Setup PictureBox customerQRCode = new PictureBox(); customerQRCode.Height = 200; customerQRCode.Width = 200; Zen.Barcode.CodeQrBarcodeDraw qrcode = Zen.Barcode.BarcodeDrawFactory.CodeQr; customerQRCode.Image = qrcode.Draw(c.ID().ToString(), customerQRCode.Height); customerQRCode.AutoSize = true; customerQRCode.SizeMode = PictureBoxSizeMode.Zoom; var bitmap = new Bitmap(customerQRCode.Height, customerQRCode.Width); customerQRCode.DrawToBitmap(bitmap, customerQRCode.ClientRectangle); ImageConverter ic = new ImageConverter(); Byte [] byteStream = (Byte[])ic.ConvertTo(bitmap, typeof(Byte[])); MemoryStream customerQR = new MemoryStream(byteStream); //SMTP Client Definition SmtpClient client = new SmtpClient(); 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("*****@*****.**", "P5:qM:7(w[/fZdfr"); //Message Content Definition MailMessage mm = new MailMessage( "*****@*****.**", c.Email); mm.Subject = "Sarre Sports | Registration"; mm.Body = String.Format( "<h1>{0}</h1></br>" + "<h3>Welcome, {1}. Thank you for registering, when you come into store please show your QR Code!</h3></br>" + "<p><b>Full Name:</b> {2}</p>" + "<p><b>Mobile No:</b> {3}</p>" + "<p><b>Customer ID:</b> {4}</p>" + "<p>If you are reading this text your email client does not support Image HTML Views.<br>Please try another email client to see your QR Code.</p>", b.BranchName(), c.FirstName, c.FullName(), c.MobileNo, c.ID()); LinkedResource LinkedImage = new LinkedResource(customerQR); LinkedImage.ContentId = "QR"; LinkedImage.ContentType = new ContentType(MediaTypeNames.Image.Jpeg); AlternateView htmlView = AlternateView.CreateAlternateViewFromString( String.Format( "<h1>{0}</h1></br>" + "<h3>Welcome, {1}. Thank you for registering, when you come into store please show your QR Code!</h3></br>" + "<p><b>Full Name:</b> {2}</p>" + "<p><b>Mobile No:</b> {3}</p>" + "<p><b>Customer ID:</b> {4}</p>" + "Your QR Code:</br><img src=cid:QR>", b.BranchName(), c.FirstName, c.FullName(), c.MobileNo, c.ID()), null, "text/html"); htmlView.LinkedResources.Add(LinkedImage); mm.AlternateViews.Add(htmlView); mm.BodyEncoding = UTF8Encoding.UTF8; mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure; try { client.Send(mm); return(true); } catch (SmtpException e) { Console.WriteLine("SMTP Error: {0}", e.StatusCode); return(false); } catch (Exception e) { Console.WriteLine("Error: {0}", e.Message); return(false); } finally { Cursor.Current = Cursors.Default; mm.Dispose(); } }
//function to send email public static void Send(EmailMessage msg) { var sErrorEmail = Object_Fido_Configs.GetAsString("fido.email.erroremail", null); var sFidoEmail = Object_Fido_Configs.GetAsString("fido.email.fidoemail", null); var sSMTPServer = Object_Fido_Configs.GetAsString("fido.email.smtpsvr", null); try { var mMessage = new MailMessage { IsBodyHtml = true }; if (!string.IsNullOrEmpty(msg.To)) { mMessage.To.Add(msg.To); } else { //Send(sErrorEmail, "", sFidoEmail, "Fido Error", "Fido Failed: No sender specified in email.", null, null); Send(new EmailMessage { To = sErrorEmail, From = sFidoEmail, Subject = "Fido Error", Body = "Fido Failed: No sender specified in email." }); } if (!string.IsNullOrEmpty(msg.CC)) { mMessage.CC.Add(msg.CC); } mMessage.From = new MailAddress(msg.From); mMessage.Body = msg.Body; mMessage.Subject = msg.Subject; if (msg.GaugeAttachment != null) { if (mMessage.Body != null) { var htmlView = AlternateView.CreateAlternateViewFromString(mMessage.Body.Trim(), null, "text/html"); for (var i = 0; i < msg.GaugeAttachment.Count(); i++) { switch (i) { case 0: var totalscore = new LinkedResource(msg.GaugeAttachment[i], "image/jpg") { ContentId = "totalscore" }; htmlView.LinkedResources.Add(totalscore); break; case 1: var userscore = new LinkedResource(msg.GaugeAttachment[i], "image/png") { ContentId = "userscore" }; htmlView.LinkedResources.Add(userscore); break; case 2: var machinescore = new LinkedResource(msg.GaugeAttachment[i], "image/png") { ContentId = "machinescore" }; htmlView.LinkedResources.Add(machinescore); break; case 3: var threatscore = new LinkedResource(msg.GaugeAttachment[i], "image/png") { ContentId = "threatscore" }; htmlView.LinkedResources.Add(threatscore); break; } } mMessage.AlternateViews.Add(htmlView); } } if (!string.IsNullOrEmpty(msg.EmailAttachment)) { var sAttachment = new Attachment(msg.EmailAttachment); mMessage.Attachments.Add(sAttachment); } using (var sSMTP = new SmtpClient(sSMTPServer)) { Console.WriteLine(@"Sending FIDO email."); var sSMTPUser = Object_Fido_Configs.GetAsString("fido.smtp.smtpuserid", string.Empty); var sSMTPPwd = Object_Fido_Configs.GetAsString("fido.smtp.smtppwd", string.Empty); sSMTP.Credentials = new NetworkCredential(sSMTPUser, sSMTPPwd); sSMTP.Send(mMessage); sSMTP.Dispose(); } } catch (Exception e) { Send(new EmailMessage { To = sErrorEmail, CC = sFidoEmail, From = sFidoEmail, Subject = "Fido Error", Body = "Fido Failed: No sender specified in email." }); //Send(sErrorEmail, sFidoEmail, sFidoEmail, "Fido Error", "Fido Failed: Generic error sending email." + e, null, null); throw; } }
/// <summary> /// Send the email now /// </summary> /// <returns></returns> public bool SendMail() { bool success = false; //MailAddress from; //MailAddress to; // execute the guard clauses this.EnsureValidData(); // set the addresses //from = (this.mailFromName != null) ? new MailAddress(this.mailFromAddress, this.mailFromName) : new MailAddress(this.mailFromAddress); //to = (this.mailToName != null) ? new MailAddress(this.mailToAddress, this.mailToName) : new MailAddress(this.mailToAddress); //// create the message //MailMessage mail = new MailMessage(from, to); MailMessage mail = new MailMessage(); foreach (string address in this.mailToAddress.Split(';')) { mail.To.Add(new MailAddress(address, this.mailToName)); } mail.From = new MailAddress(this.mailFromAddress, this.mailFromName); // set the content mail.Subject = this.mailSubject; // dual format mail if (this.mailBodyHtml != null && this.mailBodyText != null) { // create the Plain Text and html parts part AlternateView plainView = AlternateView.CreateAlternateViewFromString(this.mailBodyText, null, emailTypePlain); AlternateView htmlView = AlternateView.CreateAlternateViewFromString(this.mailBodyHtml, null, emailTypeHtml); // add to the mail message mail.AlternateViews.Add(plainView); mail.AlternateViews.Add(htmlView); } else if (this.mailBodyHtml != null) { mail.Body = this.mailBodyHtml; mail.IsBodyHtml = true; } else if (this.mailBodyText != null) { mail.Body = this.mailBodyText; } // send the message SmtpClient smtp = new SmtpClient(string.Empty); try { smtp.Send(mail); success = true; } catch { success = false; } return(success); }
static void Main(string[] args) { string mailserver = ConfigurationManager.AppSettings["mailserver"]; string teststatus = ConfigurationManager.AppSettings["test"]; string testmail = ConfigurationManager.AppSettings["testmail"].Trim(); string strSubject = "Emial Function"; string strFrom = "*****@*****.**"; string strTo = "*****@*****.**"; //ConfigurationManager.AppSettings["MailTo"]; ; string strCc = "*****@*****.**"; // ConfigurationManager.AppSettings["MailCC"]; ;// "[email protected]; [email protected]"; string strBcc = string.Empty; string strBody = "Email with table and picture template. <br >" + "Demo: <br >" + "<table border=1>" + "<tr >" + "<td><img src=\"cid:Email001\"></td>" + "<td>Column 2</td>" + "</tr>" + "</table>"; MailPriority MailPriority = 0; MailMessage clsMailSvc; clsMailSvc = new MailMessage(); AlternateView htmlBody = AlternateView.CreateAlternateViewFromString(strBody, null, "text/html"); LinkedResource lrImage = new LinkedResource(@"C:\Users\82006987\Desktop\Program\Practice\EmailPro\EmailPro\img\1.jpg", "image/gif"); lrImage.ContentId = "Email001"; htmlBody.LinkedResources.Add(lrImage); clsMailSvc.AlternateViews.Add(htmlBody); clsMailSvc.From = new MailAddress(strFrom); if (strTo != "") { string[] str = strTo.Split(';'); for (int i = 0; i < str.Length; i++) { if (str.GetValue(i).ToString() != null && str.GetValue(i).ToString().Trim() != "") { clsMailSvc.To.Add(new MailAddress(str.GetValue(i).ToString())); } } } clsMailSvc.Subject = strSubject; if (strCc != "") { string[] str = strCc.Split(';'); for (int i = 0; i < str.Length; i++) {//"The hash code for \"{0}\" is: 0x{1:X8}, {1}" if (str.GetValue(i).ToString() != null && str.GetValue(i).ToString().Trim() != "") { clsMailSvc.CC.Add(new MailAddress(str.GetValue(i).ToString())); } } } if (strBcc != "") { string[] str = strBcc.Split(';'); for (int i = 0; i < str.Length; i++) { if (str.GetValue(i).ToString() != null && str.GetValue(i).ToString().Trim() != "") { clsMailSvc.CC.Add(new MailAddress(str.GetValue(i).ToString())); } } } clsMailSvc.Body = strBody; clsMailSvc.BodyEncoding = Encoding.GetEncoding("utf-8"); clsMailSvc.IsBodyHtml = true; clsMailSvc.Priority = MailPriority; SmtpClient clsSmtpClient = new SmtpClient(mailserver); try { clsSmtpClient.Send(clsMailSvc); } catch (Exception ex) { throw ex; } }
private RestRequest GetRestRequestFromRockEmailMessage(RockEmailMessage rockEmailMessage) { var restRequest = new RestRequest(GetAttributeValue("Resource"), Method.POST); restRequest.AddParameter("domain", GetAttributeValue("Domain"), ParameterType.UrlSegment); // To rockEmailMessage.GetRecipients().ForEach(r => restRequest.AddParameter("to", new MailAddress(r.To, r.Name).ToString())); // Reply To if (rockEmailMessage.ReplyToEmail.IsNotNullOrWhiteSpace()) { var replyTo = new Parameter { Name = "h:Reply-To", Type = ParameterType.GetOrPost, Value = rockEmailMessage.ReplyToEmail }; restRequest.AddParameter(replyTo); } var fromEmailAddress = new MailAddress(rockEmailMessage.FromEmail, rockEmailMessage.FromName); restRequest.AddParameter("from", fromEmailAddress.ToString()); var safeSenderDomains = GetSafeDomains(); var fromDomain = GetEmailDomain(rockEmailMessage.FromEmail); if (safeSenderDomains.Contains(fromDomain)) { restRequest.AddParameter("h:Sender", fromEmailAddress.ToString()); } // CC rockEmailMessage .CCEmails .Where(e => e != string.Empty) .ToList() .ForEach(e => restRequest.AddParameter("cc", e)); // BCC rockEmailMessage .BCCEmails .Where(e => e != string.Empty) .ToList() .ForEach(e => restRequest.AddParameter("bcc", e)); // Subject restRequest.AddParameter("subject", rockEmailMessage.Subject); // Body (plain text) if (rockEmailMessage.PlainTextMessage.IsNotNullOrWhiteSpace()) { AlternateView plainTextView = AlternateView.CreateAlternateViewFromString(rockEmailMessage.PlainTextMessage, new ContentType(MediaTypeNames.Text.Plain)); restRequest.AddParameter("text", plainTextView); } // Body (html) restRequest.AddParameter("html", rockEmailMessage.Message); // Communication record for tracking opens & clicks AddAdditionalHeaders(restRequest, rockEmailMessage.MessageMetaData); // Attachments foreach (var attachment in rockEmailMessage.Attachments) { MemoryStream ms = new MemoryStream(); attachment.ContentStream.CopyTo(ms); restRequest.AddFile("attachment", ms.ToArray(), attachment.FileName); } return(restRequest); }
public void SendEmail(string toList, string subjectLine, string contentInPlainText, string emailFrom, string ccList, string contentInHTML) { MailMessage mail = null; try { // Verify input parameters if (string.IsNullOrEmpty(emailFrom)) { throw new Exception("Can't send email - 'From' address is null or empty"); } if (string.IsNullOrEmpty(toList)) { throw new Exception("Can't send email - 'To' address is null or empty"); } //if (fileAttachments != null) //{ // foreach (string file in fileAttachments) // { // if (!System.IO.File.Exists(file)) // { // throw new Exception("Can't send email - can't find file attachment: " + file); // } // } //} // Setup the mail message: mail = new MailMessage(); mail.Subject = subjectLine; //setting up the from address MailAddress fromMailAddress = new MailAddress(emailFrom); mail.From = fromMailAddress; //SPECIAL NOTE : NO need to set the body as adding alternate views of body will take care of it //alternate view for plain text AlternateView mailBodyPlainView = AlternateView.CreateAlternateViewFromString(contentInPlainText, new System.Net.Mime.ContentType("text/plain")); mail.AlternateViews.Add(mailBodyPlainView); //alternate view for html // Request ID : 21714 Added UTF8 Encoding as it seems to fix problems with unusual characters if (string.IsNullOrEmpty(contentInHTML) == false) { AlternateView mailBodyHTMLView = AlternateView.CreateAlternateViewFromString(contentInHTML, Encoding.UTF8, "text/html"); // attach the images to the email //if (imageList != null) //{ // foreach (RtfToHtml.SautinImage image in imageList) // { // if (image.Img != null) // { // LinkedResource linkedResource = null; // MemoryStream memoryStream = new System.IO.MemoryStream(); // image.Img.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png); // if (memoryStream != null && memoryStream.Position > 0) // { // memoryStream.Position = 0; // } // linkedResource = new LinkedResource(memoryStream); // linkedResource.ContentId = image.Cid.Replace("cid:", string.Empty); // mailBodyHTMLView.LinkedResources.Add(linkedResource); // } // } //} mail.AlternateViews.Add(mailBodyHTMLView); } // Add To email addresses: string[] ToEmailAddreses = Utility.Utility.SplitStrings(toList); foreach (string toAddress in ToEmailAddreses) { if (toAddress != null && toAddress.Trim() != string.Empty) { MailAddress to = new MailAddress(toAddress.Trim()); mail.To.Add(to); } } // Add CC email addresses if specified: string[] CCEmailAddreses = Utility.Utility.SplitStrings(ccList); if (CCEmailAddreses != null) { foreach (string ccAddress in CCEmailAddreses) { if (ccAddress != null && ccAddress.Trim() != string.Empty) { MailAddress copy = new MailAddress(ccAddress.Trim()); mail.CC.Add(copy); } } } // Add the attachments, if specified //if (fileAttachments != null) //{ // foreach (string attachment in fileAttachments) // { // Attachment data = new Attachment(attachment, System.Net.Mime.MediaTypeNames.Application.Octet); // // Add time stamp information for the file. // ContentDisposition disposition = data.ContentDisposition; // disposition.CreationDate = System.IO.File.GetCreationTime(attachment); // disposition.ModificationDate = System.IO.File.GetLastWriteTime(attachment); // disposition.ReadDate = System.IO.File.GetLastAccessTime(attachment); // // Add the file attachment to this e-mail message. // mail.Attachments.Add(data); // } //} // Now setup the mail client: SmtpClient smtpClient = new SmtpClient(this.SmtpServerName); //This block of code is for development environments: if no SMTP server name //is provided then write the emails to the file system. if (string.IsNullOrEmpty(this.SmtpServerName)) { smtpClient.PickupDirectoryLocation = System.IO.Path.GetTempPath(); smtpClient.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory; } if (this.PortNumber.HasValue) { smtpClient.Port = portNumber.Value; } if ((!string.IsNullOrEmpty(this.SmtpUsername)) && (!string.IsNullOrEmpty(this.SmtpPassword))) { smtpClient.UseDefaultCredentials = false; smtpClient.Credentials = new System.Net.NetworkCredential(this.SmtpUsername, this.SmtpPassword); } smtpClient.Send(mail); } catch (FormatException ex) { // Format exception is throw when email addresses are invalid throw ex; } catch (SmtpException ex) { //this Exception occurs when the connection to the SMTP server failed or authentication failed or The operation timed out. throw ex; } catch (Exception ex) { throw ex; } finally { if (mail != null && mail.Attachments != null) { foreach (Attachment att in mail.Attachments) { att.Dispose(); } } } }
private MailMessage CreateMailMessage(IFluentEmail email) { var data = email.Data; MailMessage message = null; // Smtp seems to require the HTML version as the alternative. if (!string.IsNullOrEmpty(data.PlaintextAlternativeBody)) { message = new MailMessage { Subject = data.Subject, Body = data.PlaintextAlternativeBody, IsBodyHtml = false, From = new MailAddress(data.FromAddress.EmailAddress, data.FromAddress.Name) }; var mimeType = new System.Net.Mime.ContentType("text/html; charset=UTF-8"); AlternateView alternate = AlternateView.CreateAlternateViewFromString(data.Body, mimeType); message.AlternateViews.Add(alternate); } else { message = new MailMessage { Subject = data.Subject, Body = data.Body, IsBodyHtml = data.IsHtml, BodyEncoding = Encoding.UTF8, SubjectEncoding = Encoding.UTF8, From = new MailAddress(data.FromAddress.EmailAddress, data.FromAddress.Name) }; } foreach (var header in data.Headers) { message.Headers.Add(header.Key, header.Value); } data.ToAddresses.ForEach(x => { message.To.Add(new MailAddress(x.EmailAddress, x.Name)); }); data.CcAddresses.ForEach(x => { message.CC.Add(new MailAddress(x.EmailAddress, x.Name)); }); data.BccAddresses.ForEach(x => { message.Bcc.Add(new MailAddress(x.EmailAddress, x.Name)); }); data.ReplyToAddresses.ForEach(x => { message.ReplyToList.Add(new MailAddress(x.EmailAddress, x.Name)); }); switch (data.Priority) { case Priority.Low: message.Priority = MailPriority.Low; break; case Priority.Normal: message.Priority = MailPriority.Normal; break; case Priority.High: message.Priority = MailPriority.High; break; } data.Attachments.ForEach(x => { System.Net.Mail.Attachment a = new System.Net.Mail.Attachment(x.Data, x.Filename, x.ContentType); a.ContentId = x.ContentId; message.Attachments.Add(a); }); return(message); }
public async Task <ActionResult> Register(RegisterViewModel model, HttpPostedFileBase image = null) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; user.FName = model.FName; user.LName = model.LName; user.Address = model.Address; user.City = model.City; user.State = model.State; user.PostalCode = model.PostCode; user.Telephone = model.Telephone; user.Latitude = model.Latitude; user.Longitude = model.Longitude; user.IpAddress = HttpContext.Request.UserHostAddress; user.AcceptTerms = model.AcceptTerms; user.Radius = "50"; if (image != null) { user.ImageMimeType = image.ContentType; user.ImageData = new byte[image.ContentLength]; image.InputStream.Read(user.ImageData, 0, image.ContentLength); } var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); MailMessage msg = new MailMessage(); var credentialUserName = ConfigurationManager.AppSettings["SendGrid_UserName"]; var sendGridPassword = ConfigurationManager.AppSettings["SendGrid_Password"]; var client = new System.Net.Mail.SmtpClient("smtp.sendgrid.net", Convert.ToInt32(587)); msg.From = new MailAddress("*****@*****.**", "RadProSite"); msg.Subject = model.Email + " " + "please validate your RadProSite account."; msg.To.Add(new MailAddress(model.Email, model.FName)); String bodyBuilder = ""; using (StreamReader reader = new StreamReader(Server.MapPath("~/Views/Shared/NewAccountValidation.html"))) { bodyBuilder += "<div align='center'>"; bodyBuilder += "<h1>Please <a style = \" outline: none;text-decoration: none;display: inline-block;color: blue;\" href=\"" + callbackUrl + "\">[ CLICK HERE ]</a> to validate your account with Radio Antenna Developers.</h1>"; bodyBuilder += "</div>"; bodyBuilder += "<div align='center'>"; bodyBuilder += "<h2>" + model.FName + " " + "you've made a smart choice!</h2>"; bodyBuilder += "</div>"; bodyBuilder += reader.ReadToEnd(); } msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(bodyBuilder, null, MediaTypeNames.Text.Html)); client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; client.UseDefaultCredentials = false; // Create the credentials: NetworkCredential credentials = new NetworkCredential(credentialUserName, sendGridPassword); client.EnableSsl = true; client.Credentials = credentials; IdentityMessage IdMess = new IdentityMessage(); SmsService sms = new SmsService(); IdMess.Destination = "1" + model.Telephone; IdMess.Subject = "Radio Antenna Developers"; IdMess.Body = "Welcome " + model.FName + " " + model.LName + " SMS Texting Phone is Valid: [" + model.Telephone + "] " + " Please check your email and activate your account. You can always update your telephone in the dashboard under Account Settings."; await sms.SendAsync(IdMess); client.Send(msg); ViewBag.Message = "Check your email and confirm your account, you must be confirmed before you can log in."; ViewBag.Name = model.FName; TempData["message"] = string.Format("{0} Welcome to Radio Antenna Developers!", model.FName); return(View("DisplayEmail")); } ViewBag.LoginTitle = "Your User name is: " + model.Email; TempData["ErrMessage"] = string.Format("{0} you have an account, try logging in again!.", model.FName); return(View(model)); } // If we got this far, something failed, redisplay form return(View(model)); }
// method that prepares and sends the two emails with an ics in each private void SendEmailWithIcsAttachment() { MailMessage msgProf = new MailMessage(); MailMessage msgStud = new MailMessage(); //Now we have to set the value to Mail message properties //Note Please change it to correct mail-id to use this in your application msgProf.From = new MailAddress(mailFromAddress, mailFromDisplayName); //sending email address msgProf.To.Add(new MailAddress(mailToAddress2, mailToDisplayName2)); // professor msgProf.Headers.Add("Content-class", "urn:content-classes:calendarmessage"); msgProf.Subject = "Office Hours Request: " + mailToDisplayName1 + " - " + mailToDisplayName2; msgProf.Body = messageBodyProf; msgStud.From = new MailAddress(mailFromAddress, mailFromDisplayName); //sending email address msgStud.To.Add(new MailAddress(mailToAddress1, mailToDisplayName1)); // student msgStud.Headers.Add("Content-class", "urn:content-classes:calendarmessage"); msgStud.Subject = "Office Hours Request: " + mailToDisplayName2 + " - " + mailToDisplayName1; msgStud.Body = messageBodyStud; // Contruct the ICS file using string builder StringBuilder str = new StringBuilder(); str.AppendLine("BEGIN:VCALENDAR"); str.AppendLine("PRODID:-//Schedule a Meeting"); str.AppendLine("VERSION:2.0"); str.AppendLine("METHOD:REQUEST"); str.AppendLine("BEGIN:VEVENT"); str.AppendLine(string.Format("DTSTART:{0:yyyyMMddTHHmmssZ}", apptStart)); str.AppendLine(string.Format("DTSTAMP:{0:yyyyMMddTHHmmssZ}", DateTime.Now)); str.AppendLine(string.Format("DTEND:{0:yyyyMMddTHHmmssZ}", apptEnd)); str.AppendLine("LOCATION: " + this.location); str.AppendLine(string.Format("UID:{0}", Guid.NewGuid())); str.AppendLine(string.Format("DESCRIPTION:{0}", msgProf.Body)); str.AppendLine(string.Format("X-ALT-DESC;FMTTYPE=text/html:{0}", msgProf.Body)); str.AppendLine(string.Format("SUMMARY:{0}", "Meeting: " + mailToDisplayName1 + " - " + mailToDisplayName2)); str.AppendLine(string.Format("ORGANIZER;CN=\"{0}\":MAILTO:{1}", msgStud.To[0].DisplayName, msgStud.To[0].Address)); str.AppendLine(string.Format("ATTENDEE;CN=\"{0}\";RSVP=TRUE:mailto:{1}", msgProf.To[0].DisplayName, msgProf.To[0].Address)); str.AppendLine(string.Format("ATTENDEE;CN=\"{0}\";RSVP=FALSE:mailto:{1}", msgStud.To[0].DisplayName, msgStud.To[0].Address)); str.AppendLine("BEGIN:VALARM"); str.AppendLine("TRIGGER:-PT15M"); str.AppendLine("ACTION:DISPLAY"); str.AppendLine("DESCRIPTION:Reminder"); str.AppendLine("END:VALARM"); str.AppendLine("END:VEVENT"); str.AppendLine("END:VCALENDAR"); //Now sending an email with attachment ICS file. //System.Net.Mail.SmtpClient smtpclient = new System.Net.Mail.SmtpClient(); System.Net.Mail.SmtpClient smtpclient = new System.Net.Mail.SmtpClient(mailServerAddress, this.port); //smtpclient.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials; smtpclient.Credentials = new NetworkCredential(userName, pword); smtpclient.EnableSsl = true; System.Net.Mime.ContentType contype = new System.Net.Mime.ContentType("text/calendar"); contype.Parameters.Add("method", "REQUEST"); contype.Parameters.Add("name", "Meeting.ics"); AlternateView avCal = AlternateView.CreateAlternateViewFromString(str.ToString(), contype); msgProf.AlternateViews.Add(avCal); msgStud.AlternateViews.Add(avCal); smtpclient.Send(msgStud); smtpclient.Send(msgProf); }
public bool SendMail(Templates template, Dictionary <string, string> dataBody, string[] fields, string[] fieldsRequire, string subject, MailAddressCollection addressTo, MailAddressCollection addressCC = null, MailAddressCollection addressCCO = null) { bool sendMail = false; try { string directoryTemplate = Path.Combine(templateDirectory); string fileName = template.GetAttributeOfType <DescriptionAttribute>().Description; string fullPathFile = Path.Combine(basePath, directoryTemplate, fileName); if (!File.Exists(fullPathFile)) { throw new Exception($"No se encontró la ruta especificada: {fullPathFile}"); } string templateBody = File.ReadAllText(fullPathFile); string[] fieldsNotExists, fieldsRequireWithNullValue; ValidateDataBody(templateBody, dataBody, fields, fieldsRequire, out templateBody, out fieldsNotExists, out fieldsRequireWithNullValue); if (fieldsNotExists.Length > 0) { throw new Exception($"No se encontraron los siguientes campos: {string.Join(", ", fieldsNotExists)}"); } if (fieldsRequireWithNullValue.Length > 0) { throw new Exception($"Los siguientes campos requeridos no tienen valor: {string.Join(", ", fieldsRequireWithNullValue)}"); } MailMessage mail = new MailMessage(); mail.From = new MailAddress(addressFrom, displayNameFrom); if (addressTo == null) { throw new Exception("No existe datos del destinatario"); } if (addressTo.Count == 0) { throw new Exception("No existe datos del destinatario"); } AddAddressCollection(mail.To, addressTo); AddAddressCollection(mail.CC, addressCC); AddAddressCollection(mail.Bcc, addressCCO); ServicePointManager.ServerCertificateValidationCallback = delegate(object s , X509Certificate certificate , X509Chain chain , SslPolicyErrors sslPolicyErrors) { return(true); }; mail.Subject = subject; AlternateView viewHtml = AlternateView.CreateAlternateViewFromString(templateBody, Encoding.UTF8, MediaTypeNames.Text.Html); Dictionary <string, Dictionary <string, string> > images = new Dictionary <string, Dictionary <string, string> > { ["imagenMEM"] = new Dictionary <string, string> { ["logo-minem.jpg"] = MediaTypeNames.Image.Jpeg }, //["imagenBanner"] = new Dictionary<string, string> { ["sres-logo.png"] = "image/png" }, ["imagenGEF"] = new Dictionary <string, string> { ["logo_gef.jpg"] = MediaTypeNames.Image.Jpeg }, ["imagenPNUD"] = new Dictionary <string, string> { ["logo_pnud.jpg"] = MediaTypeNames.Image.Jpeg }, //["imagenFRECUENTE"] = new Dictionary<string, string> { ["preguntas_frecuentes_email.jpg"] = MediaTypeNames.Image.Jpeg }, //["imagenCINTA"] = new Dictionary<string, string> { ["cinta.png"] = "image/png" }, //["imagenLAZO"] = new Dictionary<string, string> { ["lazo.png"] = "image/png" } }; AddImages(viewHtml, images); mail.AlternateViews.Add(viewHtml); smtp.Send(mail); sendMail = true; } catch (Exception ex) { Log.Error(ex); } return(sendMail); }
private MailMessage GetMailMessageFromRockEmailMessage(RockEmailMessage rockEmailMessage) { var mailMessage = new MailMessage { IsBodyHtml = true, Priority = MailPriority.Normal }; // From mailMessage.From = new MailAddress(rockEmailMessage.FromEmail, rockEmailMessage.FromName); // Reply to try { if (rockEmailMessage.ReplyToEmail.IsNotNullOrWhiteSpace()) { mailMessage.ReplyToList.Add(new MailAddress(rockEmailMessage.ReplyToEmail)); } } catch { } // To var recipients = rockEmailMessage.GetRecipients().ToList(); recipients.ForEach(r => mailMessage.To.Add(new MailAddress(r.To, r.Name))); // cc rockEmailMessage .CCEmails .Where(e => e.IsNotNullOrWhiteSpace()) .ToList() .ForEach(e => mailMessage.CC.Add(new MailAddress(e))); // bcc rockEmailMessage .BCCEmails .Where(e => e.IsNotNullOrWhiteSpace()) .ToList() .ForEach(e => mailMessage.Bcc.Add(new MailAddress(e))); // Subject mailMessage.Subject = rockEmailMessage.Subject; // Plain text if (rockEmailMessage.PlainTextMessage.IsNotNullOrWhiteSpace()) { var plainTextView = AlternateView.CreateAlternateViewFromString(rockEmailMessage.PlainTextMessage, new System.Net.Mime.ContentType(MediaTypeNames.Text.Plain)); mailMessage.AlternateViews.Add(plainTextView); } // Body var htmlBody = rockEmailMessage.Message; if (!string.IsNullOrWhiteSpace(htmlBody)) { if (rockEmailMessage.CssInliningEnabled) { // Move styles inline to ensure compatibility with a wider range of email clients. htmlBody = htmlBody.ConvertHtmlStylesToInlineAttributes(); } var htmlView = AlternateView.CreateAlternateViewFromString(htmlBody, new System.Net.Mime.ContentType(MediaTypeNames.Text.Html)); mailMessage.AlternateViews.Add(htmlView); } if (rockEmailMessage.Attachments.Any()) { foreach (var attachment in rockEmailMessage.Attachments) { if (attachment != null) { mailMessage.Attachments.Add(new Attachment(attachment.ContentStream, attachment.FileName)); } } } AddAdditionalHeaders(mailMessage, rockEmailMessage.MessageMetaData); return(mailMessage); }
protected void btnRegister_Click(object sender, System.EventArgs e) { //Add user into list and log them in if (IsValid) { user = (User)Session["tempUser"]; Session.Remove("tempUser"); //If user ticked register as admin box a confirmation email will be sent if (user.IsAdmin) { user.FirstName = ((TextBox)FindControl("firstName")).Text; user.LastName = ((TextBox)FindControl("lastName")).Text; user.Street = ((TextBox)FindControl("streetAddress")).Text; user.Suburb = ((TextBox)FindControl("suburb")).Text; user.Postcode = ((TextBox)FindControl("postCode")).Text; user.DOB = ((TextBox)FindControl("birthDate")).Text; user.Phone = ((TextBox)FindControl("firstName")).Text; QueryClass.AddUser(user); //Accessing gmail account to send email SmtpClient client = new SmtpClient(); client.DeliveryMethod = SmtpDeliveryMethod.Network; client.EnableSsl = true; client.Host = "smtp.gmail.com"; client.Port = 587; System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("*****@*****.**", "bhpassword"); client.UseDefaultCredentials = false; client.Credentials = credentials; MailMessage msg = new MailMessage(); msg.From = new MailAddress("*****@*****.**"); msg.To.Add(new MailAddress(user.Email)); msg.Subject = "Bobblehead - Confirm Admin Status"; //If html does not exist return non-html email msg.Body = ConfirmAdminMessage(false, user.Email, user.FirstName, user.LastName); //create an alternate HTML view that includes images and formatting string html = ConfirmAdminMessage(true, user.Email, user.FirstName, user.LastName); AlternateView view = AlternateView .CreateAlternateViewFromString( html, null, "text/html"); //Adding an image to the email string imgPath = Server.MapPath("../img/bobblebuttlogo.png"); LinkedResource img = new LinkedResource(imgPath); img.ContentId = "logoImage"; view.LinkedResources.Add(img); //add the HTML view to the message and send msg.AlternateViews.Add(view); try { client.Send(msg); //Send to main page with pop message about sent email Response.Redirect("Main?confirmAdmin="); } catch { lblRegEmail.Text = "Email could not be sent"; lblRegEmail.Visible = true; } } //If user registered as non admin no email confirmation will be sent else { user.FirstName = ((TextBox)FindControl("firstName")).Text; user.LastName = ((TextBox)FindControl("lastName")).Text; user.Street = ((TextBox)FindControl("streetAddress")).Text; user.Suburb = ((TextBox)FindControl("suburb")).Text; user.Postcode = ((TextBox)FindControl("postCode")).Text; user.DOB = ((TextBox)FindControl("birthDate")).Text; user.Phone = ((TextBox)FindControl("firstName")).Text; QueryClass.AddUser(user); Session.Add("user", user); Response.Redirect("Main"); } } }
public static void SendMeetingRequest(CalendarBasicModel c, List <KeyValuePair <string, string> > emailAddresses, string meetingType, string ssd) { string sender = "*****@*****.**"; //ConfigurationSettings.AppSettings["Sender"].ToString(); string userName = "******"; //ConfigurationSettings.AppSettings["UserName"].ToString(); string password = "******"; //ConfigurationSettings.AppSettings["Password"].ToString(); string smtpURL = "smtp.sendgrid.net"; //ConfigurationSettings.AppSettings["SmtpURL"].ToString(); int smtpPort = 587; //ConfigurationSettings.AppSettings["Port"].ToString(); try { MailMessage msg = new MailMessage(); msg.From = new MailAddress(sender); foreach (KeyValuePair <string, string> email in emailAddresses) { msg.To.Add(new MailAddress(email.Value, email.Key)); } msg.Subject = meetingType + " Invitation"; msg.Body = c.text; System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType("text/calendar"); ct.Parameters.Add("method", "REQUEST"); ct.Parameters.Add("name", "Meeting.ics"); StringBuilder str = new StringBuilder(); str.AppendLine("BEGIN:VCALENDAR"); str.AppendLine("PRODID:-//Microsoft Corporation//Outlook 14.0 MIMEDIR//EN"); str.AppendLine("VERSION:2.0"); str.AppendLine("METHOD:REQUEST"); TimeZoneInfo localZone = TimeZoneInfo.Local; str.AppendLine("BEGIN:VTIMEZONE"); str.AppendLine(string.Format("TZID:{0}", localZone.Id)); //str.AppendLine("BEGIN:STANDARD"); //str.AppendLine("DTSTART:16010101T000000"); //str.AppendLine("TZOFFSETFROM:+0530"); //str.AppendLine("TZOFFSETTO:+0530"); //str.AppendLine("END:STANDARD"); str.AppendLine("END:VTIMEZONE"); str.AppendLine("BEGIN:VEVENT"); if (c.event_pid != 0 && c.rec_type == "") { str.AppendLine("DTSTART:" + DateTime.Parse(c.start_date).ToString(d.format)); str.AppendLine("DTEND:" + DateTime.Parse(c.end_date).ToString(d.format)); str.AppendLine("RECURRENCE-ID:" + UnixTimeStampToDateTime(c.event_length).ToString(d.format)); // str.AppendLine("RECURRENCE-ID:" + DateTime.Parse(c.end_date).ToString(d.format));//UnixTimeStampToDateTime(c.event_length).ToString(d.format)); str.AppendLine("UID:" + c.event_pid); // DateTime.Parse( } else if (c.rec_type != "" && c.event_pid == 0) { str.AppendLine("DTSTART:" + getStartTimeevent(c)); str.AppendLine("DTEND:" + getEndTimeevent(c)); str.AppendLine("RRULE:" + getRrule(c)); string exdate = getExdate(c.id, c); if (exdate != "0") { str.AppendLine("EXDATE:" + exdate); } str.AppendLine("UID:" + c.id); } else if (c.rec_type == "" && c.event_pid == 0) { str.AppendLine("DTSTART:" + DateTime.Parse(c.start_date).ToString(d.format)); str.AppendLine("DTEND:" + DateTime.Parse(c.end_date).ToString(d.format)); str.AppendLine("UID:" + c.id); } // str.AppendLine(string.Format("DTSTAMP:{0:yyyyMMddTHHmmssZ}", DateTime.UtcNow)); // str.AppendLine("When: " + string.Format("DTSTART:{0:yyyyMMddTHHmmssZ}", DateTime.Parse(dtStartDate.ToString(), null, DateTimeStyles.AdjustToUniversal) + string.Format("DTEND:{0:yyyyMMddTHHmmssZ}", DateTime.Parse(dtEndDate.ToString(), null, DateTimeStyles.AdjustToUniversal)))); str.AppendLine("LOCATION: " + "Static Content"); str.AppendLine(string.Format("DESCRIPTION:{0}", msg.Body)); str.AppendLine(string.Format("X-ALT-DESC;FMTTYPE=text/html:{0}", msg.Body)); str.AppendLine(string.Format("SUMMARY:{0}", msg.Subject)); str.AppendLine(string.Format("ORGANIZER:MAILTO:{0}", msg.From.Address)); str.AppendLine(string.Format("ATTENDEE;CN=\"{0}\";RSVP=TRUE:mailto:{1}", msg.To[0].DisplayName, msg.To[0].Address)); str.AppendLine("BEGIN:VALARM"); str.AppendLine("TRIGGER:-PT15M"); str.AppendLine("ACTION:DISPLAY"); str.AppendLine("DESCRIPTION:Reminder"); str.AppendLine("END:VALARM"); str.AppendLine("END:VEVENT"); str.AppendLine("END:VCALENDAR"); // AlternateView htmlView = AlternateView.CreateAlternateViewFromString(str.ToString(), new System.Net.Mime.ContentType("text/html; method=request; charset=UTF-8;component=vevent")); AlternateView avCal = AlternateView.CreateAlternateViewFromString(str.ToString(), ct); msg.AlternateViews.Add(avCal); // msg.AlternateViews.Add(htmlView); SmtpClient clt = new SmtpClient(smtpURL); clt.Port = smtpPort; clt.Credentials = new System.Net.NetworkCredential(userName, password); clt.EnableSsl = true; msg.IsBodyHtml = true; msg.BodyEncoding = Encoding.UTF8; // System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) { return true; }; clt.Send(msg); } catch (Exception ex) { throw ex; } }
public LinkedResourceCollectionTest() { lrc = AlternateView.CreateAlternateViewFromString("test", new ContentType("text/plain")).LinkedResources; lr = LinkedResource.CreateLinkedResourceFromString("test", new ContentType("text/plain")); }
public void enviar() { try { System.Net.Mail.MailMessage mailNoti = new System.Net.Mail.MailMessage(); mailNoti.From = new MailAddress(mailUser); foreach (string mailTo in strmailTo) { mailNoti.To.Add(mailTo); } foreach (string mailCC in strCC) { mailNoti.CC.Add(mailCC); } foreach (string mailCCO in strCCO) { mailNoti.Bcc.Add(mailCCO); } mailNoti.Subject = this.asunto; mailNoti.IsBodyHtml = true; AlternateView htmlView = AlternateView.CreateAlternateViewFromString(strBody.ToString(), Encoding.UTF8, MediaTypeNames.Text.Html); foreach (ArchivoMail imagen in lstImagen) { LinkedResource img = new LinkedResource(imagen.Ruta, MediaTypeNames.Image.Jpeg); img.ContentId = imagen.Name; htmlView.LinkedResources.Add(img); } mailNoti.AlternateViews.Add(htmlView); //foreach (ArchivoMail archivo in lstArchivo) //{ // Attachment adj = new Attachment(archivo.Ruta); // mailNoti.Attachments.Add(adj); //} if (arrArchivosRuta != null) { foreach (var item in arrArchivosRuta) { if (item != null) { Attachment adj = new Attachment(item); mailNoti.Attachments.Add(adj); } } } mailNoti.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess; mailNoti.Priority = System.Net.Mail.MailPriority.High; SmtpClient smtpNoti = new SmtpClient(); smtpNoti.UseDefaultCredentials = false; smtpNoti.Credentials = new System.Net.NetworkCredential(UserCredencial, PasswordCredencial, DominioCredencial);//, // smtpNoti.Host = Host; smtpNoti.DeliveryMethod = SmtpDeliveryMethod.Network; // smtpNoti.EnableSsl = true; smtpNoti.TargetName = "STARTTLS/smtp.office365.com"; smtpNoti.Port = 587; // smtpNoti.Send(mailNoti); } catch (Exception ex) { throw ex; } }
public void Serv_EnvioCorreosRol() { Conexiones con = new Conexiones(); string Asunto = string.Empty; string Cuerpo = string.Empty; string ListaCorreosEnviados = string.Empty; try { var Lista = con.GetCabecerasSinProcesar(); if (Lista.Count == 0) { Lista = con.GetCabecerasProcesadasAmedias(); } var Credenciales = con.GetInfoCredenciales(); if (Credenciales.ID == 0) return; foreach (var Rol in Lista) { ListaCorreosEnviados = string.Empty; foreach (var Emp in Rol.Lista) { MemoryStream mem = new MemoryStream(); try { Asunto = Credenciales.Asunto; Asunto = Asunto.Replace("[Mes]", Emp.infoRpt.cro_fecini.ToString("MMMM")); Asunto = Asunto.Replace("[Anio]", Emp.infoRpt.cro_fecini.ToString("yyyy")); Asunto = Asunto.Replace("[NombreEmpleado]", Emp.infoRpt.NOM); Cuerpo = Credenciales.Cuerpo; Cuerpo = Cuerpo.Replace("[Mes]", Emp.infoRpt.cro_fecini.ToString("MMMM")); Cuerpo = Cuerpo.Replace("[Anio]", Emp.infoRpt.cro_fecini.ToString("yyyy")); Cuerpo = Cuerpo.Replace("[NombreEmpleado]", Emp.infoRpt.NOM); #region Armar cuerpo del correo correo MailMessage mail = new MailMessage(); mail.From = new MailAddress(Credenciales.Usuario);//Correo de envio mail.Subject = Asunto; if (!string.IsNullOrEmpty(Emp.trb_email == null ? "" : Emp.trb_email.Trim())) { string Correo = new string(Emp.trb_email.Trim().Where(c => !char.IsControl(c)).ToArray()); mail.To.Add(Correo); } else mail.To.Add(Credenciales.CorreoCopia); string Body = Cuerpo; Rol01_Rpt rpt = new Rol01_Rpt(); rpt.info = Emp.infoRpt; rpt.ExportToPdf(mem); // Create a new attachment and put the PDF report into it. mem.Seek(0, System.IO.SeekOrigin.Begin); Attachment att = new Attachment(mem, "ROL" + Emp.infoRpt.cro_fecfin.ToString("yyyyMM") + ".pdf", "application/pdf"); mail.Attachments.Add(att); AlternateView htmlView = AlternateView.CreateAlternateViewFromString(Body, null, "text/html"); mail.AlternateViews.Add(htmlView); #endregion #region smtp SmtpClient smtp = new SmtpClient(); smtp.UseDefaultCredentials = false; smtp.Host = Credenciales.host; smtp.EnableSsl = Credenciales.PermitirSSL; smtp.Port = Credenciales.Puerto; smtp.Credentials = new NetworkCredential(Credenciales.Usuario, Credenciales.Contrasenia); smtp.Send(mail); #endregion ListaCorreosEnviados += "OK " + Emp.infoRpt.NOM.Trim() + " " + (Emp.trb_email ?? "").Trim() + "</br>"; Console.WriteLine("OK " + Emp.infoRpt.NOM.Trim() + " " + (Emp.trb_email ?? "").Trim()); } catch (Exception ex) { con.GuardarExcepcion(new Mail_LogError_Info { Metodo = "EnviarCorreoSMTP", Error = ex == null ? string.Empty : (ex.Message ?? string.Empty), InnerException = ex == null || ex.InnerException == null ? string.Empty : (ex.InnerException.Message.Length > 1000 ? ex.InnerException.Message.Substring(0, 1000) : ex.InnerException.Message) }); Emp.Error = ex.Message; ListaCorreosEnviados += "ERROR " + Emp.infoRpt.NOM.Trim() + " " + (Emp.trb_email ?? "").Trim() + "</br>"; Console.WriteLine("ERROR " + Emp.infoRpt.NOM.Trim() + " " + (Emp.trb_email ?? "").Trim()); try { MemoryStream memError = new MemoryStream(); #region Armar cuerpo del correo correo MailMessage mail = new MailMessage(); mail.From = new MailAddress(Credenciales.Usuario);//Correo de envio mail.Subject = Asunto; mail.To.Add(Credenciales.CorreoCopia); string Body = Cuerpo; Rol01_Rpt rpt = new Rol01_Rpt(); rpt.info = Emp.infoRpt; rpt.ExportToPdf(memError); // Create a new attachment and put the PDF report into it. memError.Seek(0, System.IO.SeekOrigin.Begin); Attachment att = new Attachment(memError, "ROL" + Emp.infoRpt.cro_fecfin.ToString("yyyyMM") + ".pdf", "application/pdf"); mail.Attachments.Add(att); AlternateView htmlView = AlternateView.CreateAlternateViewFromString(Body, null, "text/html"); mail.AlternateViews.Add(htmlView); #endregion #region smtp SmtpClient smtp = new SmtpClient(); smtp.UseDefaultCredentials = false; smtp.Host = Credenciales.host; smtp.EnableSsl = Credenciales.PermitirSSL; smtp.Port = Credenciales.Puerto; smtp.Credentials = new NetworkCredential(Credenciales.Usuario, Credenciales.Contrasenia); smtp.Send(mail); #endregion } catch (Exception er) { con.GuardarExcepcion(new Mail_LogError_Info { Metodo = "EnviarCorreoSMTP", Error = er == null ? string.Empty : (er.Message ?? string.Empty), InnerException = er == null || er.InnerException == null ? string.Empty : (er.InnerException.Message.Length > 1000 ? er.InnerException.Message.Substring(0, 1000) : er.InnerException.Message) }); } } mem.Close(); mem.Flush(); con.ModificarDet(Emp); con.Modificar(Rol); } try { #region Armar cuerpo del correo correo MailMessage mail = new MailMessage(); mail.From = new MailAddress(Credenciales.Usuario);//Correo de envio mail.Subject = "RESUMEN CORREOS ENVIADOS"; mail.To.Add(Credenciales.CorreoCopia); string Body = ListaCorreosEnviados; #endregion #region smtp SmtpClient smtp = new SmtpClient(); smtp.UseDefaultCredentials = false; smtp.Host = Credenciales.host; smtp.EnableSsl = Credenciales.PermitirSSL; smtp.Port = Credenciales.Puerto; smtp.Credentials = new NetworkCredential(Credenciales.Usuario, Credenciales.Contrasenia); smtp.Send(mail); #endregion } catch (Exception ex) { } } } catch (Exception ex) { con.GuardarExcepcion(new Mail_LogError_Info { Metodo = "EnviarCorreo", Error = ex == null ? string.Empty : (ex.Message ?? string.Empty), InnerException = ex == null || ex.InnerException == null ? string.Empty : (ex.InnerException.Message.Length > 1000 ? ex.InnerException.Message.Substring(0, 1000) : ex.InnerException.Message) }); } }
private void EnviaEmail(string error) { try { Sesion session = new Sesion(); session = (Sesion)Session["Sesion" + Session.SessionID]; ConfiguracionGlobal configuracion = new ConfiguracionGlobal(); configuracion.Id_Cd = session.Id_Cd_Ver; configuracion.Id_Emp = session.Id_Emp; CN_Configuracion cn_configuracion = new CN_Configuracion(); cn_configuracion.Consulta(ref configuracion, session.Emp_Cnx); StringBuilder cuerpo_correo = new StringBuilder(); cuerpo_correo.Append("<div align='center'>"); cuerpo_correo.Append(" <table>"); cuerpo_correo.Append(" <tr>"); cuerpo_correo.Append(" <td><img src=\"cid:companylogo\"></td>"); cuerpo_correo.Append(" <td valign='middle' style='text-decoration: underline'><b><font face= 'Tahoma' size = '4'>Error Envio Orden de Compra SUCURSAL#" + session.Id_Cd_Ver + " </font></b></td>"); cuerpo_correo.Append(" </tr>"); cuerpo_correo.Append(" <tr>"); cuerpo_correo.Append(" <td colspan='2'><br><br><br></td>"); cuerpo_correo.Append(" </tr>"); cuerpo_correo.Append(" <tr>"); cuerpo_correo.Append(" <td colspan='2'><b><font face= 'Tahoma' size = '2'>Error</font></b></td>"); cuerpo_correo.Append(" </tr>"); cuerpo_correo.Append(" <tr>"); cuerpo_correo.Append(" <td colspan='2'><br><br></td>"); cuerpo_correo.Append(" </tr>"); cuerpo_correo.Append(" <tr>"); cuerpo_correo.Append(" <td align='left' colspan='2'><b><font face= 'Tahoma' size = '2' color='#777777'>" + error); cuerpo_correo.Append("</font></b></td>"); cuerpo_correo.Append(" </tr>"); cuerpo_correo.Append(" <tr>"); cuerpo_correo.Append(" <td colspan='2'><br><br></td>"); cuerpo_correo.Append(" </tr>"); cuerpo_correo.Append(" <tr>"); cuerpo_correo.Append(" </table>"); cuerpo_correo.Append("</div>"); SmtpClient sm = new SmtpClient(configuracion.Mail_Servidor, Convert.ToInt32(configuracion.Mail_Puerto)); sm.Credentials = new NetworkCredential(configuracion.Mail_Usuario, configuracion.Mail_Contraseña); MailMessage m = new MailMessage(); m.From = new MailAddress(configuracion.Mail_Remitente); string To = "*****@*****.**"; m.To.Add(new MailAddress(To)); m.Subject = "Error Envio Orden de Compra #" + session.Id_Cd_Ver; m.IsBodyHtml = true; string body = cuerpo_correo.ToString(); AlternateView vistaHtml = AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html); //Esto queda dentro de un try por si llegan a cambiar la imagen el correo como quiera se mande try { LinkedResource logo = new LinkedResource(MapPath(@"Imagenes/logo.jpg"), MediaTypeNames.Image.Jpeg); logo.ContentId = "companylogo"; vistaHtml.LinkedResources.Add(logo); } catch (Exception) { } m.AlternateViews.Add(vistaHtml); sm.Send(m); } catch (Exception) { Alerta("Error al enviar el correo. Favor de revisar la configuración del sistema"); } }
/// <summary> /// send email /// </summary> /// <param name="request"></param> /// <param name="callbackUrl"></param> /// <param name="message"></param> /// <returns></returns> public bool SendEmail(DbTables.MembershipRequest request, string callbackUrl, string message) { try { var mailMsg = new MailMessage(); // To mailMsg.To.Add(new MailAddress(request.Email, request.Fname + " " + request.Lname)); // From mailMsg.From = new MailAddress("*****@*****.**", "Butterfly Friends"); // Subject and multipart/alternative Body if (callbackUrl == null) //no callbackurl, request is declined { mailMsg.Subject = "Medlemskap avist"; if (message != "") { var text = "Vi beklager å måtte melde at din forespørsel om medlamskap har blitt avist. \n\n" + message + "\n\nMvh, \nButterfly Friends"; var html = @"<p>Vi beklager å måtte melde at din forespørsel om medlamskap har blitt avist.<br><br>" + message + "<br><br>Mvh,<br>Butterfly Friends</p>"; mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(text, null, MediaTypeNames.Text.Plain)); mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html)); } else { var text = "Vi beklager å måtte melde at din forespørsel om medlamskap har blitt avist. \n\nMvh, \nButterfly Friends"; var html = @"<p>Vi beklager å måtte melde at din forespørsel om medlamskap har blitt avist.<br><br>Mvh,<br>Butterfly Friends</p>"; mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(text, null, MediaTypeNames.Text.Plain)); mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html)); } } else { mailMsg.Subject = "Medlemskap akseptert"; //Request accepted if (message != "") { var text = "Ditt medlemskap har blitt akseptert og vi er veldig glad for å ha deg med på laget! \n\nDitt passord kan settes her: " + callbackUrl + "\nDette kan også byttes på dine profilsider.\n\n" + message + "\n\nMvh, \nButterfly Friends"; var html = @"<p>Ditt medlemskap har blitt akseptert og vi er veldig glad for å ha deg med på laget!<br><br>Ditt passord kan settes <a href=" + callbackUrl + ">her</a>.<br>Dette kan ogsp byttes på dine profilsider.<br><br>" + message + "<br><br>Mvh,<br>Butterfly Friends</p>"; mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(text, null, //add both html and normal bodies to email MediaTypeNames.Text.Plain)); mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html)); } else { var text = "Ditt medlemskap har blitt akseptert og vi er veldig glad for å ha deg med på laget! \n\nDitt passord kan settes her: " + callbackUrl + "\nDette kan også byttes på dine profilsider.\n\nMvh, \nButterfly Friends"; var html = @"<p>Ditt medlemskap har blitt akseptert og vi er veldig glad for å ha deg med på laget!<br><br>Ditt kan passord settes <a href=" + callbackUrl + ">her</a>.<br>Dette kan også byttes på dine profilsider.<br><br>Mvh,<br>Butterfly Friends</p>"; mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(text, null, MediaTypeNames.Text.Plain)); mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html)); } } // Init SmtpClient and send var smtpClient = new SmtpClient("smtp.sendgrid.net", Convert.ToInt32(587)); var SendGridAPIList = _context.SendGridAPI.ToList(); var SendGridAPI = new DbTables.SendGridAPI(); if (SendGridAPIList.Any()) { SendGridAPI = SendGridAPIList.First(); if (!SendGridAPI.Enabeled) { return(true); } } else { return(false); } var credentials = new NetworkCredential(SendGridAPI.UserName, SendGridAPI.PassWord); smtpClient.Credentials = credentials; smtpClient.Send(mailMsg); //send email } catch (Exception) { return(false); } return(true); //email successfully sent }
public Task SendAsync(IdentityMessage message) { // MailMessage email = new MailMessage("*****@*****.**", message.Destination); // email.Subject = message.Subject; // email.Body = message.Body; // email.IsBodyHtml = true; // string password = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("Montana@11")); // var mailClient = new SmtpClient("smtp.sendgrid.net", 587) { Credentials = new NetworkCredential("infodatixUser",password), EnableSsl = false}; // return mailClient.SendMailAsync(email); //return Task.FromResult(0); string destinaton, cc; MailAddress ccAddress = null; if (message.Destination.IndexOf(";") > -1) { destinaton = message.Destination.Split(';')[0]; cc = message.Destination.Split(';')[1]; ccAddress = new MailAddress(cc); } else { destinaton = message.Destination; } System.Net.Mail.MailMessage email = new System.Net.Mail.MailMessage("*****@*****.**", destinaton); if (!string.IsNullOrEmpty(_attachment)) { Attachment attach = new Attachment(_attachment); email.Attachments.Add(attach); } string[] splitedata = message.Subject.Split('<'); email.Subject = splitedata[0]; if (splitedata.Length > 1) { email.Body = message.Body; email.IsBodyHtml = true; if (ccAddress != null) { email.CC.Add(ccAddress); } LinkedResource logo = new LinkedResource(splitedata[1]); logo.ContentId = "companyLogo"; //message.Body=message.Body.Replace("<%image%>","<img src='cid:companyLogo' style='height: 100px;float: left;margin-right: 10px;margin-bottom: 8px;'/>"); AlternateView av = AlternateView.CreateAlternateViewFromString(message.Body, null, MediaTypeNames.Text.Html); av.LinkedResources.Add(logo); email.AlternateViews.Add(av); email.IsBodyHtml = true; var mailClient = new SmtpClient("smtp.gmail.com", 587) { Credentials = new NetworkCredential("*****@*****.**", "popup$$1234"), EnableSsl = true }; return(mailClient.SendMailAsync(email)); } else { email.Body = message.Body; AlternateView av = AlternateView.CreateAlternateViewFromString(message.Body, null, MediaTypeNames.Text.Html); email.AlternateViews.Add(av); var mailClient = new SmtpClient("smtp.gmail.com", 587) { Credentials = new NetworkCredential("*****@*****.**", "popup$$1234"), EnableSsl = true }; return(mailClient.SendMailAsync(email)); } }
public MailMessage SendMultiple(string from, string to, string cc, string bcc, string subject, string body, bool ReturnMsg) { //if (SmtpNetworkUser != "") // from = SmtpNetworkUser; MailMessage msg = new MailMessage(); //set sender's address msg.From = new MailAddress(from); msg.Subject = subject; msg.Body = body; // Allow multiple "To" addresses to be separated by a semi-colon if (to.Trim().Length > 0) { foreach (string add in to.Split(';')) { msg.To.Add(new MailAddress(add)); } } // Allow multiple "Cc" addresses to be separated by a semi-colon if (cc.Trim().Length > 0) { foreach (string add in cc.Split(';')) { msg.CC.Add(new MailAddress(add)); } } // Allow multiple "Bcc" addresses to be separated by a semi-colon if (bcc.Trim().Length > 0) { foreach (string add in bcc.Split(';')) { msg.Bcc.Add(new MailAddress(add)); } } //System.Web.HttpContext.Current.Response.Write(string.Format(" - {0} {1} {2} {3}", // from, to, subject, body)); NameValueCollection Images = new NameValueCollection(); int autoId = 1; StringBuilder ret = new StringBuilder(); int i = body.IndexOf("src=\""); int j = 0; int len = body.Length; try { while (i > 0) { ret.Append(body.Substring(0, i + 5)); body = body.Substring(i + 5); //WebContext.Response.Write(i.ToString() + " - <pre>" + WebContext.Server.HtmlEncode(body) + "</pre>"); i = body.IndexOf("\""); string image = body.Substring(0, i); //ret.Append(image); Images.Add(string.Format("Image{0}", autoId), WebContext.Server.MapPath(image)); //ret.Append("\""); body = body.Substring(image.Length + 1); image = "cid:" + string.Format("Image{0}", autoId); ret.Append(image); ret.Append("\""); autoId++; i = body.IndexOf("src=\""); //WebContext.Response.Write(image + "<BR />"); } ret.Append(body); //WebContext.Response.Write(ret.ToString()); } catch { } body = ret.ToString(); AlternateView htmlView = AlternateView.CreateAlternateViewFromString(body, null, "text/html"); foreach (string key in Images.Keys) { try { LinkedResource imagelink = new LinkedResource(Images[key], "image/jpg"); imagelink.ContentId = key; //imagelink.TransferEncoding = System.Net.Mime.TransferEncoding.Base64; htmlView.LinkedResources.Add(imagelink); } catch (Exception Ex) { WebContext.Response.Write(Ex.Message); } } msg.AlternateViews.Add(htmlView); //msg.IsBodyHtml = true; msg.Body = body; try { smtp.Send(msg); lw.WebTools.WebContext.Response.Write("Message sent"); //MailQueue.AddToQueue(msg); } catch (Exception Ex) { lw.WebTools.WebContext.Response.Write("Error"); throw (Ex); } if (!ReturnMsg) { msg = null; } return(msg); }
private void EnviaRelFacRegXCorreo(ref NegocioPF.Facturas oFacturas, int folio) { try { NegocioPF.Proveedor oProveedor = new NegocioPF.Proveedor(); oProveedor.Cargar(txtEmisor.Text.Substring(0, txtEmisor.Text.IndexOf(" "))); string sHtml = "<html>"; sHtml += "<table style='font-family:arial;color:black;font-size:12px; text-align:justify' border='0' width=\"800\">"; sHtml += "<tr><td><p>" + ((Idioma)Session["oIdioma"]).Texto("MsgSaludo") + "</p></td></tr>"; sHtml += "<tr><td></td></tr>"; sHtml += "<tr><td><p>" + ((Idioma)Session["oIdioma"]).Texto("MsgRelFacReg") + " " + folio.ToString() + ":</p></td></tr>"; sHtml += "<tr><td></td></tr>"; if (oFacturas.Datos.Tables[0].Rows.Count > 0) { sHtml += "<tr><td><table style='font-family:arial;color:black;font-size:12px; text-align:justify' border='1' cellspacing='0' cellpadding='2' width=\"800\">"; sHtml += "<tr>"; sHtml += "<td style='background:#F8EFFB; text-align:center; width=80px'> " + grdFacturas.Columns[0].HeaderText + "</td>"; sHtml += "<td style='background:#F8EFFB; text-align:center; width=150px'>" + grdFacturas.Columns[1].HeaderText + "</td>"; sHtml += "<td style='background:#F8EFFB; text-align:center; width=100px'>" + grdFacturas.Columns[2].HeaderText + "</td>"; sHtml += "<td style='background:#F8EFFB; text-align:center; width=100px'>" + grdFacturas.Columns[3].HeaderText + "</td>"; sHtml += "<td style='background:#F8EFFB; text-align:center; width=50px'>" + grdFacturas.Columns[4].HeaderText + "</td>"; //sHtml += "<td style='background:#F8EFFB; text-align:center; width=80px'>" + grdFacturas.Columns[5].HeaderText + "</td>"; //sHtml += "<td style='background:#F8EFFB; text-align:center; width=100px'>" + grdFacturas.Columns[6].HeaderText + "</td>"; //sHtml += "<td style='background:#F8EFFB; text-align:center; width=100px'>" + grdFacturas.Columns[7].HeaderText + "</td>"; sHtml += "</tr>"; foreach (GridViewRow r in grdFacturas.Rows) { sHtml += "<tr>"; sHtml += "<td style='width=80px;'>" + r.Cells[0].Text + "</td>"; sHtml += "<td style='width=150px;'>" + r.Cells[1].Text + "</td>"; sHtml += "<td style='width=100px;'>" + r.Cells[2].Text + "</td>"; sHtml += "<td style='width=100px;'>" + r.Cells[3].Text + "</td>"; sHtml += "<td style='width=50px;'>" + r.Cells[4].Text + "</td>"; //sHtml += "<td style='width=80px;'>" + r.Cells[5].Text + "</td>"; //sHtml += "<td style='width=100px;'>" + r.Cells[6].Text + "</td>"; //sHtml += "<td style='width=100px;'>" + r.Cells[7].Text + "</td>"; sHtml += "</tr>"; } sHtml += "</table></td></tr>"; } sHtml += "<tr><td></td></tr>"; sHtml += "<tr><td>" + ((Idioma)Session["oIdioma"]).Texto("Saludos") + "</td></tr>"; sHtml += "<tr><td></td></tr>"; sHtml += "<tr><td><img src=cid:FirmaPF></td></tr>"; sHtml += "</table>"; sHtml += "</Html>"; EmailTemplate oEmail = new EmailTemplate(""); oEmail.To.Add(oProveedor.eMail); oEmail.From = new MailAddress(@System.Configuration.ConfigurationSettings.AppSettings["EmailFrom"], "PortalFacturas", System.Text.Encoding.UTF8); oEmail.Subject = ((Idioma)Session["oIdioma"]).Texto("FacturasRegistradas") + " " + ((Idioma)Session["oIdioma"]).Texto("ConElFolio").ToLower() + " " + folio.ToString(); //Agrega Logo AlternateView altView = AlternateView.CreateAlternateViewFromString(sHtml, null, MediaTypeNames.Text.Html); string imageSource = (Server.MapPath("") + "\\Images\\FirmaPF.jpg"); LinkedResource PictureRes = new LinkedResource(imageSource, MediaTypeNames.Image.Jpeg); PictureRes.ContentId = "FirmaPF"; altView.LinkedResources.Add(PictureRes); oEmail.AlternateViews.Add(altView); try { oEmail.Send(); } catch (Exception ex) { throw new Exception("MsgFacRegEnvCorreo"); } } catch (Exception ex) { throw ex; } }
/// <summary> /// Sends an email /// </summary> /// <param name="MessageBody">The body of the message</param> public override void SendMail(string MessageBody = "") { using (MailMessage Mail = new MailMessage()) { using (AlternateView TextView = AlternateView.CreateAlternateViewFromString(AppointmentInfo.ToString(), new System.Net.Mime.ContentType("text/plain"))) { using (AlternateView HTMLView = AlternateView.CreateAlternateViewFromString(AppointmentInfo.GetHCalendar(), new System.Net.Mime.ContentType("text/html"))) { System.Net.Mime.ContentType CalendarType = new System.Net.Mime.ContentType("text/calendar"); CalendarType.Parameters.Add("method", AppointmentInfo.Cancel ? "CANCEL" : "REQUEST"); CalendarType.Parameters.Add("name", "meeting.ics"); using (AlternateView CalendarView = AlternateView.CreateAlternateViewFromString(AppointmentInfo.GetICalendar(), CalendarType)) { CalendarView.TransferEncoding = System.Net.Mime.TransferEncoding.SevenBit; Mail.AlternateViews.Add(TextView); Mail.AlternateViews.Add(HTMLView); Mail.AlternateViews.Add(CalendarView); char[] Splitter = { ',', ';' }; string[] AddressCollection = To.Split(Splitter); for (int x = 0; x < AddressCollection.Length; ++x) { if (!string.IsNullOrEmpty(AddressCollection[x].Trim())) { Mail.To.Add(AddressCollection[x]); } } if (!string.IsNullOrEmpty(CC)) { AddressCollection = CC.Split(Splitter); for (int x = 0; x < AddressCollection.Length; ++x) { if (!string.IsNullOrEmpty(AddressCollection[x].Trim())) { Mail.CC.Add(AddressCollection[x]); } } } if (!string.IsNullOrEmpty(Bcc)) { AddressCollection = Bcc.Split(Splitter); for (int x = 0; x < AddressCollection.Length; ++x) { if (!string.IsNullOrEmpty(AddressCollection[x].Trim())) { Mail.Bcc.Add(AddressCollection[x]); } } } Mail.From = new MailAddress(From); Mail.Subject = Subject; foreach (Attachment Attachment in Attachments) { Mail.Attachments.Add(Attachment); } Mail.Priority = Priority; Mail.SubjectEncoding = System.Text.Encoding.GetEncoding("ISO-8859-1"); Mail.BodyEncoding = System.Text.Encoding.GetEncoding("ISO-8859-1"); using (System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(Server, Port)) { if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password)) { smtp.Credentials = new System.Net.NetworkCredential(UserName, Password); } if (UseSSL) { smtp.EnableSsl = true; } else { smtp.EnableSsl = false; } smtp.Send(Mail); } } } } } }
/// <summary> /// Internal send message /// </summary> /// <param name="Message2">Message</param> protected override void InternalSend(Interfaces.IMessage Message2) { var Message = Message2 as EmailMessage; if (Message == null) { return; } if (string.IsNullOrEmpty(Message.Body)) { Message.Body = " "; } using (System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage()) { char[] Splitter = { ',', ';' }; string[] AddressCollection = Message.To.Split(Splitter); for (int x = 0; x < AddressCollection.Length; ++x) { if (!string.IsNullOrEmpty(AddressCollection[x].Trim())) { message.To.Add(AddressCollection[x]); } } if (!string.IsNullOrEmpty(Message.CC)) { AddressCollection = Message.CC.Split(Splitter); for (int x = 0; x < AddressCollection.Length; ++x) { if (!string.IsNullOrEmpty(AddressCollection[x].Trim())) { message.CC.Add(AddressCollection[x]); } } } if (!string.IsNullOrEmpty(Message.Bcc)) { AddressCollection = Message.Bcc.Split(Splitter); for (int x = 0; x < AddressCollection.Length; ++x) { if (!string.IsNullOrEmpty(AddressCollection[x].Trim())) { message.Bcc.Add(AddressCollection[x]); } } } message.Subject = Message.Subject; if (!string.IsNullOrEmpty(Message.From)) { message.From = new System.Net.Mail.MailAddress(Message.From); } using (AlternateView BodyView = AlternateView.CreateAlternateViewFromString(Message.Body, null, MediaTypeNames.Text.Html)) { foreach (LinkedResource Resource in Message.EmbeddedResources.Check(new List <LinkedResource>())) { BodyView.LinkedResources.Add(Resource); } message.AlternateViews.Add(BodyView); message.Priority = Message.Priority; message.SubjectEncoding = System.Text.Encoding.GetEncoding("ISO-8859-1"); message.BodyEncoding = System.Text.Encoding.GetEncoding("ISO-8859-1"); message.IsBodyHtml = true; foreach (Attachment TempAttachment in Message.Attachments.Check(new List <Attachment>())) { message.Attachments.Add(TempAttachment); } if (!string.IsNullOrEmpty(Message.Server)) { SendMessage(new System.Net.Mail.SmtpClient(Message.Server, Message.Port), Message, message); } else { SendMessage(new SmtpClient(), Message, message); } } } }