public Task SendAsync(IdentityMessage message, Stream attachment, string CC = null) { SmtpClient smtp = new SmtpClient(); MailMessage mail = new MailMessage(); mail.From = new MailAddress(ConfigurationManager.AppSettings["systemEmail"]); mail.To.Add(message.Destination); mail.Bcc.Add(new MailAddress(ConfigurationManager.AppSettings["ordersEmail"])); mail.Bcc.Add(new MailAddress(ConfigurationManager.AppSettings["developerIdentity"])); mail.Subject = message.Subject; if (attachment != null) { System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Application.Pdf); System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(attachment, ct); attach.ContentDisposition.FileName = "Locarno Sun Dried Fruit Order"; mail.Attachments.Add(attach); } string body = string.Format("<html><body><table>{0}<tr><td><br />Thank you for using the © Locarno Sun Dried Fruit platform</td></tr><tr><td><br /><img src=cid:LogoImage></td></tr></table></body></html>", message.Body); AlternateView htmlView = AlternateView.CreateAlternateViewFromString(body.Trim(), null, "text/html"); string fileNameLogo = HttpContext.Current.Server.MapPath("~/Content/Images/Logopng.png"); System.Net.Mail.LinkedResource imageResource = new System.Net.Mail.LinkedResource(fileNameLogo, "image/png"); imageResource.ContentId = "LogoImage"; htmlView.LinkedResources.Add(imageResource); mail.AlternateViews.Add(htmlView); smtp.Send(mail); return(Task.FromResult(0)); }
public override void SendMessage(HtmlMailMessage message) { if (message.To.Count > 0) { SmtpClient client = new SmtpClient(); AlternateView avHtml = AlternateView.CreateAlternateViewFromString( message.Body, null, System.Net.Mime.MediaTypeNames.Text.Html); string textBody = "You must use an e-mail client that supports HTML messages"; // Create an alternate view for unsupported clients AlternateView avText = AlternateView.CreateAlternateViewFromString( textBody, null, System.Net.Mime.MediaTypeNames.Text.Plain); foreach (KeyValuePair<string, Stream> item in message.LinkedResources) { LinkedResource linkedresource = new LinkedResource( item.Value, System.Net.Mime.MediaTypeNames.Image.Jpeg); linkedresource.ContentId = item.Key; avHtml.LinkedResources.Add(linkedresource); } message.AlternateViews.Add(avHtml); message.AlternateViews.Add(avText); client.Send(message); } }
static void Main(string[] args) { MailMessage m = new MailMessage("*****@*****.**", "*****@*****.**", "Blah blah blah", "Blah blah body."); MailMessage n = new MailMessage(new MailAddress("*****@*****.**", "Lance Tucker"), new MailAddress("*****@*****.**", "Ben Miller")); // Bored now because I've done all this before. m.Attachments.Add(new Attachment(@"C:\windows\win.ini")); Stream sr = new FileStream(@"C:\Attachment.txt", FileMode.Open, FileAccess.Read); m.Attachments.Add(new Attachment(sr, "myfile.txt", MediaTypeNames.Application.Octet)); string htmlBody = "<html><body><h1>MyMessage</h1|><br>This is an HTML message.<img src=\"cid:Pic1\"></body></html>"; //m.IsBodyHtml = true; AlternateView avHtml = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html); LinkedResource pic1 = new LinkedResource("pic.jpg", MediaTypeNames.Image.Jpeg); pic1.ContentId = "Pic1"; avHtml.LinkedResources.Add(pic1); string textBody = "You must use an e-mail client that supports HTML messages"; AlternateView avText = AlternateView.CreateAlternateViewFromString(textBody, null, MediaTypeNames.Text.Plain); m.AlternateViews.Add(avHtml); m.AlternateViews.Add(avText); SmtpClient client = new SmtpClient("smtp.contoso.com"); client.Send(m); }
public override MailContent CreateMailContent() { GraphControl graphControl = CreateControlImpl(); MailContent mailContent = new MailContent(); MemoryStream ms = new MemoryStream(); graphControl.ChartInstance.SaveImage( ms, ChartImageFormat.Png ); ms.Position = 0; LinkedResource imgLink = new LinkedResource(ms, "image/png") { ContentId = "chart1" }; mailContent.Resource = imgLink; mailContent.Message = string.Format( @"Graph image:<br> <img src=""cid:chart1"" width=""{0}"" height=""{1}"" > ", Preprocessor.GraphicsInfo.Size.Width, Preprocessor.GraphicsInfo.Size.Height ); return mailContent; }
public Task SendAsync(string subject, string destination, string cc, string bodyContent) { SmtpClient smtp = new SmtpClient(); MailMessage mail = new MailMessage(); mail.From = new MailAddress(ConfigurationManager.AppSettings["systemEmail"]); mail.To.Add(destination); if (ConfigurationManager.AppSettings["ccTimeFreightManagement"] == "true" && !string.IsNullOrEmpty(cc)) { mail.CC.Add(new MailAddress(cc)); } mail.Bcc.Add(new MailAddress(ConfigurationManager.AppSettings["ordersEmail"])); mail.Bcc.Add(new MailAddress(ConfigurationManager.AppSettings["developerIdentity"])); mail.Subject = subject; string body = string.Format("<html><body><table>{0}<tr><td><br />Thank you for using the © Locarno Sun Dried Fruit platform</td></tr><tr><td><br /><img src=cid:LogoImage></td></tr></table></body></html>", EmailService.Borderify(bodyContent)); AlternateView htmlView = AlternateView.CreateAlternateViewFromString(body.Trim(), null, "text/html"); string fileNameLogo = HttpContext.Current.Server.MapPath("~/Content/Images/Logopng.png"); System.Net.Mail.LinkedResource imageResource = new System.Net.Mail.LinkedResource(fileNameLogo, "image/png"); imageResource.ContentId = "LogoImage"; htmlView.LinkedResources.Add(imageResource); mail.AlternateViews.Add(htmlView); smtp.Send(mail); return(Task.FromResult(0)); }
public EmailSendingResult SendEmail(EmailArguments emailArguments) { var sendResult = new EmailSendingResult(); sendResult.EmailSendingFailureMessage = string.Empty; try { var mailMessage = new MailMessage(emailArguments.From, emailArguments.To); mailMessage.Subject = emailArguments.Subject; mailMessage.Body = emailArguments.Message; mailMessage.IsBodyHtml = emailArguments.Html; var client = new SmtpClient(emailArguments.SmtpServer); if (emailArguments.EmbeddedResources != null && emailArguments.EmbeddedResources.Count > 0) { AlternateView avHtml = AlternateView.CreateAlternateViewFromString(emailArguments.Message, Encoding.UTF8, MediaTypeNames.Text.Html); foreach (EmbeddedEmailResource resource in emailArguments.EmbeddedResources) { LinkedResource linkedResource = new LinkedResource(resource.ResourceStream, resource.ResourceType.ToSystemNetResourceType()); linkedResource.ContentId = resource.EmbeddedResourceContentId; avHtml.LinkedResources.Add(linkedResource); } mailMessage.AlternateViews.Add(avHtml); } client.Send(mailMessage); sendResult.EmailSentSuccessfully = true; } catch (Exception ex) { sendResult.EmailSendingFailureMessage = ex.Message; } return sendResult; }
//[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); }
private static void SendEmail(NotificationData notify, string body) { MailMessage mailMsg = new MailMessage(); mailMsg.From = new MailAddress("*****@*****.**", "Kellogg's Keep Safe Module"); // TEMPORARY USE ONLY!!! //mailMsg.Bcc.Add(new MailAddress("*****@*****.**", "Melissa Snow")); // TEMPORARY USE ONLY!!! mailMsg.Subject = "Kellogg's Keep Safe Module - Assignment received"; //MailAddress mailTo = new MailAddress(address, name); //MailAddress mailTo = new MailAddress("*****@*****.**", "Melissa Snow"); MailAddress mailTo = new MailAddress("*****@*****.**", "Dave Arbuckle"); mailMsg.To.Add(mailTo); AlternateView htmlView = null; htmlView = AlternateView.CreateAlternateViewFromString(body); LinkedResource ksImage = new LinkedResource(Assembly.GetExecutingAssembly().GetManifestResourceStream("AssignmentNotificationEmail.Images.KeepSafe-logo-v6-sml.gif")); ksImage.ContentId = "keepsafe"; htmlView.LinkedResources.Add(ksImage); ksImage = new LinkedResource(Assembly.GetExecutingAssembly().GetManifestResourceStream("AssignmentNotificationEmail.Images.University.png")); ksImage.ContentId = "training"; htmlView.LinkedResources.Add(ksImage); htmlView.ContentType = new ContentType("text/html"); mailMsg.AlternateViews.Add(htmlView); using (SmtpClient smtp = new SmtpClient("192.168.1.12")) { Console.WriteLine("Mail to " + mailMsg.To[0].Address); smtp.Send(mailMsg); LogTheSentEmail(notify.NotificationID); System.Threading.Thread.Sleep(250); } }
public static MailMessage AddHtmlView(this MailMessage mail, string htmlBody, List<string> resources, IResourceResolver resourceResolver) { if (mail != null && htmlBody.Clear() != null && resources != null && resources.Any()) { if (resourceResolver == null) { throw new Exception("ResourceResolver not set"); } AlternateView av = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html); resources.ForEach(r => { HtmlResource hr = resourceResolver.GetHtmlResource(r); if (hr != null) { MemoryStream ms = new MemoryStream(hr.Content); LinkedResource lr; if (hr.MediaType.Clear() != null) { lr = new LinkedResource(ms, hr.MediaType.Clear()); } else { lr = new LinkedResource(ms); } lr.ContentId = hr.ContentId; av.LinkedResources.Add(lr); } mail.AlternateViews.Add(av); }); } return mail; }
static void Main() { string filePath = @"..\..\Images\publicdiscussionbanner.jpg"; //string emailBody = "<html><body><h1>Picture</h1><br><p>This is some picture!</p><img src=\"publicdiscussionbanner.jpg\"></body></html>"; string emailBody = @"<html> <body> <br>" + "<img src=\"publicdiscussionbanner.jpg\">" + @"<h1>Oбществено обсъждане</h1> <p>Проектът се осъществява с финансовата подкрепа на Оперативна програма “Административен капацитет”, съфинансирана от Европейския съюз чрез Европейския социален фонд.!</p> <div> <p> Уважаеми господин Манчев, Това е тестови имейл, чиято цел е да ви накара да цъкнете на следния линк <br> <a href='www.dir.bg'>Цък!</a> Благодарим за вниманието! </p> </div> <footer> СМ Консулта 2015 </footer> </body> </html>"; AlternateView avHtml = AlternateView.CreateAlternateViewFromString (emailBody, null, MediaTypeNames.Text.Html); LinkedResource inline = new LinkedResource(filePath, MediaTypeNames.Image.Jpeg); inline.ContentId = Guid.NewGuid().ToString(); avHtml.LinkedResources.Add(inline); MailMessage mail = new MailMessage("*****@*****.**", "*****@*****.**"); mail.AlternateViews.Add(avHtml); mail.IsBodyHtml = true; mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess; mail.Body = String.Format( "<h3>Client: " + inline.ContentStream + " Has Sent You A Screenshot</h3>" + @"<img src=""cid:{0}"" />", inline.ContentId); Attachment att = new Attachment(filePath); att.ContentDisposition.Inline = true; mail.Attachments.Add(att); using (SmtpClient client = new SmtpClient("10.10.10.18")) { //client.EnableSsl = true; client.UseDefaultCredentials = false; client.Credentials = new NetworkCredential("*****@*****.**", "smcsupport12"); client.DeliveryMethod = SmtpDeliveryMethod.Network; client.Send(mail); } }
public void SendNotification(string[] addresses, string title, string message, LinkedResource linkedResource) { this.Addresses = addresses; this.Title = title; this.Message = message; this.SendNotificationInvoked = true; this.LinkedResource = LinkedResource; }
public virtual Email AddLinkedResource(string fileName, string contentType, string cid) { LinkedResource link = new System.Net.Mail.LinkedResource(fileName, contentType); link.ContentId = cid; linkeds.Add(link); return(this); }
public string sendMail(string userdisplayname, string to, string from, string subject, string msg, string path) { string str = ""; SmtpClient client = new SmtpClient { Credentials = new NetworkCredential(username, passwd), Port = port, Host = hostname, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, Timeout = 20000 }; this.mail = new MailMessage(); string[] strArray = to.Split(new char[] { ',' }); try { this.mail.From = new MailAddress(from, userdisplayname, Encoding.UTF8); for (byte i = 0; i < strArray.Length; i = (byte)(i + 1)) { this.mail.To.Add(strArray[i]); } this.mail.Priority = MailPriority.High; this.mail.Subject = subject; this.mail.Body = msg; if (path != "") { LinkedResource item = new LinkedResource(path) { ContentId = "Logo" }; AlternateView view = AlternateView.CreateAlternateViewFromString("<html><body><table border=2><tr width=100%><td><img src=cid:Logo alt=companyname /></td><td>FROM BLUEFROST</td></tr></table><hr/></body></html>" + msg, null, "text/html"); view.LinkedResources.Add(item); this.mail.AlternateViews.Add(view); this.mail.IsBodyHtml = true; this.mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure; this.mail.ReplyTo = new MailAddress(to); client.Send(this.mail); return str; } if (path == "") { this.mail.IsBodyHtml = true; this.mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure; this.mail.ReplyTo = new MailAddress(to); client.Send(this.mail); str = "good"; } } catch (Exception exception) { if (exception.ToString() == "The operation has timed out") { client.Send(this.mail); str = "bad"; } } return str; }
private void Init(XmlDocument xmlTemplate) { XmlElement documentElement = xmlTemplate.DocumentElement; base.subject = xmlTemplate.SelectSingleNode("/email-template/subject").InnerText.Trim(); base.from = xmlTemplate.SelectSingleNode("/email-template/addresses/entry[@name='From']").Attributes["value"].InnerText; base.to = xmlTemplate.SelectSingleNode("/email-template/addresses/entry[@name='To']").Attributes["value"].InnerText; XmlNode node = xmlTemplate.SelectSingleNode("/email-template/addresses/entry[@name='Cc']"); if (node != null) { base.cc = node.Attributes["value"].InnerText; } XmlNode node2 = xmlTemplate.SelectSingleNode("/email-template/addresses/entry[@name='Bcc']"); if (node2 != null) { base.bcc = node2.Attributes["value"].InnerText; } base.body = xmlTemplate.SelectSingleNode("/email-template/body").InnerText.Trim(); base.bodyContentType = xmlTemplate.SelectSingleNode("/email-template/body/@format").InnerText; string innerText = xmlTemplate.SelectSingleNode("/email-template/body/@encoding").InnerText; try { base.bodyEncoding = Encoding.GetEncoding(innerText); } catch { base.bodyEncoding = Encoding.GetEncoding("iso-8859-1"); } XmlNodeList list = xmlTemplate.SelectNodes("/email-template/embeddedResources/resource"); if ((list != null) && (list.Count > 0)) { string directoryName = Path.GetDirectoryName(this.xmlTemplateFile); foreach (XmlNode node3 in list) { try { string str3 = node3.Attributes["name"].Value; string str4 = node3.Attributes["path"].Value; string str5 = "application/octet-stream"; if (node3.Attributes["content-type"] != null) { str5 = node3.Attributes["content-type"].Value; } if (!(string.IsNullOrEmpty(str3) || string.IsNullOrEmpty(str4))) { LinkedResource item = new LinkedResource(Path.Combine(directoryName, str4)); item.ContentId = str3; item.ContentType.Name = str3; item.ContentType.MediaType = str5; base.LinkedResources.Add(item); } } catch (Exception exception) { throw new InvalidEmailTemplateException("<embeddedResources> node is not in correct format.\r\n Example:\r\n <embeddedResources>\r\n <resource name=\"logo\" path=\"images\\logo.gif\" content-type=\"image/jpeg\"/>\r\n </embeddedResources>", exception); } } } }
public void SendNotification(string[] addresses, string title, string messageTemplate, LinkedResource linkedResource, IDictionary<string, string> messageParameters) { this.Addresses = addresses; this.Title = title; this.MessageTemplate = messageTemplate; this.Parameters = messageParameters; this.SendNotificationInvoked = true; this.LinkedResource = LinkedResource; }
public static void SendReport() { SI.Controls.LookFeel.SetupJamesPurple(); MailMessage msg = new MailMessage("*****@*****.**", "*****@*****.**", "invoice spreads", "body"); msg.To.Clear(); msg.CC.Add("*****@*****.**"); //msg.To.Add("*****@*****.**"); //msg.To.Add("*****@*****.**"); //msg.To.Add("*****@*****.**"); var con = InvoiceSpreadGenerator.GetInvoiceSpreadsAsConstruct(); var path = string.Format(@"c:\temp\invoiceSpreads_{0}.csv", DateTime.Today.ToString("yyyyMMdd")); con.WriteToCSV(path); var bodyBuilder = new StringBuilder(); var resourceDict = new Dictionary<string, string>(); addChart(bodyBuilder, new InvoiceSpreadStructures.TU_1_Libor(), resourceDict); addChart(bodyBuilder, new InvoiceSpreadStructures.TU_2_Libor(), resourceDict); addChart(bodyBuilder, new InvoiceSpreadStructures.TY_1_Libor(), resourceDict); addChart(bodyBuilder, new InvoiceSpreadStructures.TY_2_Libor(), resourceDict); addChart(bodyBuilder, new InvoiceSpreadStructures.FV_1_Libor(), resourceDict); addChart(bodyBuilder, new InvoiceSpreadStructures.FV_2_Libor(), resourceDict); addChart(bodyBuilder, new InvoiceSpreadStructures.FVTY_1_Libor(), resourceDict); addChart(bodyBuilder, new InvoiceSpreadStructures.FVTY_2_Libor(), resourceDict); addChart(bodyBuilder, new InvoiceSpreadStructures.TUFV_1_Libor(), resourceDict); addChart(bodyBuilder, new InvoiceSpreadStructures.TUFV_2_Libor(), resourceDict); msg.Body = bodyBuilder.ToString(); msg.IsBodyHtml = true; AlternateView htmlView = AlternateView.CreateAlternateViewFromString(msg.Body, null, "text/html"); foreach (var k in resourceDict.Keys) { LinkedResource lr = new LinkedResource(resourceDict[k]) { ContentId = k }; htmlView.LinkedResources.Add(lr); } msg.AlternateViews.Add(htmlView); msg.Attachments.Add(new Attachment(path)); try { Emailer.GetClient().Send(msg); } catch (Exception ex_) { Logger.Error("Error sending mail", typeof (InvoiceSpreadReportGenerator), ex_); } }
private async Task<LinkedResource> CreateEmbeddedImageAsync(string path, string CID) { return await Task.Run(() => { LinkedResource image = new LinkedResource(path); image.ContentId = CID; image.ContentType = new ContentType("image/jpg"); return image; }); }
public void SendNotification(string[] addresses, string title, string htmlMessage, LinkedResource linkedResource, IDictionary<string, string> messageParameters) { foreach (var messageParameter in messageParameters) { htmlMessage = htmlMessage.Replace(messageParameter.Key, messageParameter.Value); } this.SendNotification(addresses, title, htmlMessage, linkedResource, false); }
private SerializableLinkedResource(LinkedResource resource) { ContentLink = resource.ContentLink; ContentId = resource.ContentId; ContentStream = new MemoryStream(); resource.ContentStream.CopyTo(ContentStream); resource.ContentStream.Position = 0; ContentType = resource.ContentType; TransferEncoding = resource.TransferEncoding; }
internal LinkedResource GetLinkedResource() { LinkedResource slr = new LinkedResource(_contentStream); slr.ContentId = _contentId; slr.ContentLink = _contentLink; slr.ContentType = _contentType.GetContentType(); slr.TransferEncoding = _transferEncoding; return slr; }
public static void SendEmail(string FromEmail, string FromDispalyName, string ToList, string Subject, string HtmBody, IEnumerable<string> EmbedImagePathList, String BCCList = "") { AlternateView avHtml = AlternateView.CreateAlternateViewFromString(HtmBody, null, MediaTypeNames.Text.Html); foreach (var em in EmbedImagePathList) { LinkedResource pic1 = new LinkedResource(HttpContext.Current.Server.MapPath(em), MediaTypeNames.Image.Jpeg) { ContentId = Path.GetFileNameWithoutExtension(HttpContext.Current.Server.MapPath(em)) }; avHtml.LinkedResources.Add(pic1); } SendEmail(FromEmail, FromDispalyName, ToList, Subject, HtmBody, BCCList, avHtml); }
public void SendEmailMessage(String toEmailAddrList,String senderName,String subject,String body,String attachmentsFilePathList,String logoPath, String companyDescription) { var smtpServer = new SmtpClient { Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["SmtpEmail"], ConfigurationManager.AppSettings["SmtpPassword"]), Port = 587, Host = "smtp.gmail.com", EnableSsl = true }; _mail = new MailMessage(); var addr = toEmailAddrList.Split(','); try { _mail.From = new MailAddress(ConfigurationManager.AppSettings["SmtpEmail"], senderName, System.Text.Encoding.UTF8); Byte i; for (i = 0; i < addr.Length; i++) _mail.To.Add(addr[i]); _mail.Subject = subject; _mail.Body = body; if (attachmentsFilePathList != null) { var attachments = attachmentsFilePathList.Split(','); for (i = 0; i < attachments.Length; i++) _mail.Attachments.Add(new Attachment(attachments[i])); } _path = logoPath; if (_path != null) { var logo = new LinkedResource(_path) {ContentId = "Logo"}; string htmlview = "<html><body><table border=2><tr width=100%><td><img src=cid:Logo alt=companyname /></td><td>" + companyDescription + "</td></tr></table><hr/></body></html>"; var alternateView1 = AlternateView.CreateAlternateViewFromString(htmlview + body, null, MediaTypeNames.Text.Html); alternateView1.LinkedResources.Add(logo); _mail.AlternateViews.Add(alternateView1); } else { var alternateView1 = AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html); _mail.AlternateViews.Add(alternateView1); } _mail.IsBodyHtml = true; _mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure; //mail.ReplyToList = new MailAddress(ConfigurationManager.AppSettings["SmtpEmail"].ToString()); smtpServer.Send(_mail); } catch (Exception ex) { _logger.Error("Exception occured while sending email",ex); } }
//public void SendEmail(List<string> To, string Subject, string Body, List<string> Attached, string From, string Password, string MailServer, int Port, out string msjError) //{ // msjError = string.Empty; // MailMessage email = new MailMessage(); // foreach (string to in To) // { // foreach (string t in to.Split(';')) // { // if (!string.IsNullOrEmpty(t)) // { // try // { // email.To.Add(new MailAddress(t)); // } // catch (Exception ex) // { // msjError = $"{msjError}||Error agregando cuenta destino: {t} => {ex.Message}"; // } // } // } // } // email.From = new MailAddress(From); // email.Subject = Subject; // email.Body = Body; // email.IsBodyHtml = true; // email.Priority = MailPriority.Normal; // foreach (string file in Attached) // { // try // { // email.Attachments.Add(new Attachment(file)); // } // catch (Exception ex) // { // msjError = $"{msjError}||Error agregando archivo a adjuntos: {file} => {ex.Message}"; // } // } // SmtpClient smtp = new SmtpClient // { // Host = MailServer, // Port = Port, // EnableSsl = false, // UseDefaultCredentials = false, // Credentials = new NetworkCredential(From, Password) // }; // // // smtp.Send(email); // smtp.Dispose(); // email.Dispose(); //} public void SendEmail(List <string> To, string Subject, string Body, List <string> Attached, string From, string Password, string MailServer, int Port, out string msjError) { msjError = string.Empty; try { SmtpClient client = new SmtpClient(); client.Port = Port; client.Host = MailServer; client.EnableSsl = false; client.Timeout = 1000000000; client.DeliveryMethod = SmtpDeliveryMethod.Network; client.UseDefaultCredentials = true; client.Credentials = new NetworkCredential(From, Password); MailMessage mail = new MailMessage(); mail.From = new MailAddress(From); mail.Subject = Subject; foreach (string to in To) { mail.To.Add(new MailAddress(to)); } AlternateView htmlView = AlternateView.CreateAlternateViewFromString("<div><img src=cid:companylogo></div><div>" + Body + "</div>", null, "text/html"); mail.BodyEncoding = UTF8Encoding.UTF8; mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure; System.Net.Mail.LinkedResource imageResource = new System.Net.Mail.LinkedResource(System.AppDomain.CurrentDomain.BaseDirectory + @"img\logo.png"); imageResource.ContentId = "companylogo"; htmlView.LinkedResources.Add(imageResource); mail.AlternateViews.Add(htmlView); mail.BodyEncoding = UTF8Encoding.UTF8; mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure; foreach (string file in Attached) { try { mail.Attachments.Add(new Attachment(file)); } catch (Exception ex) { msjError = $"{msjError}||Error agregando archivo a adjuntos: {file} => {ex.Message}"; } } client.Send(mail); client.Send(mail); } catch (Exception ex) { msjError = ex.Message; } }
public SerializableLinkedResource(LinkedResource linkedResource) { ContentId = linkedResource.ContentId; ContentLink = linkedResource.ContentLink; ContentType = new SerializableContentType(linkedResource.ContentType); TransferEncoding = linkedResource.TransferEncoding; if (linkedResource.ContentStream != null) { var bytes = new byte[linkedResource.ContentStream.Length]; linkedResource.ContentStream.Read(bytes, 0, bytes.Length); ContentStream = new MemoryStream(bytes); } }
/// <summary> /// Gửi email đầy đủ thông tin /// </summary> /// <param name="Email">Email người gửi</param> /// <param name="EmailPassword">Email password</param> /// <param name="Port">Port email</param> /// <param name="From">Email người gửi</param> /// <param name="To">Email người nhận</param> /// <param name="Cc">Email người cùng nhận được nhìn thấy trên mail</param> /// <param name="Bcc">Email người cùng nhận không nhìn thấy trên mail</param> /// <param name="Subject">Tiêu đề</param> /// <param name="Body">Nội dung</param> /// <param name="Attachments">File định kèm</param> public static void Send(String Email, string EmailPassword, int Port, String From, String To, String Cc, String Bcc, String Subject, String Body, String Attachments) { // Tài khoản gmail sử dụng để phát mail var mail = new SmtpClient("smtp.gmail.com", Port) { Credentials = new NetworkCredential(Email, EmailPassword), EnableSsl = true }; AlternateView avHtml = AlternateView.CreateAlternateViewFromString(Body, null, MediaTypeNames.Text.Html); var imageLocation = HttpContext.Current.Server.MapPath("~/Content/images/logo.png"); LinkedResource pic1 = new LinkedResource(imageLocation); pic1.ContentId = "Pic1"; avHtml.LinkedResources.Add(pic1); // Mail Message var message = new MailMessage(); message.AlternateViews.Add(avHtml); message.IsBodyHtml = true; message.SubjectEncoding = Encoding.UTF8; message.BodyEncoding = Encoding.UTF8; message.From = new MailAddress(From); message.To.Add(new MailAddress(To)); message.Subject = Subject; //message.Body = Body; message.ReplyToList.Add(message.From); if (!String.IsNullOrEmpty(Cc)) { message.CC.Add(Regex.Replace(Cc, @"[,;\s]+", ",")); } if (!String.IsNullOrEmpty(Bcc)) { message.Bcc.Add(Regex.Replace(Bcc, @"[,;\s]+", ",")); } if (!String.IsNullOrEmpty(Attachments)) { var filenames = Attachments.Split(',', ';'); foreach (var filename in filenames) { message.Attachments.Add(new Attachment(filename.Trim())); } } // Send mail message mail.Send(message); }
public bool sendMail(string from, string password, Customer customer) { try { m.From = new MailAddress(from); m.To.Add(new MailAddress(customer.email)); //m.Body = message; m.Subject = "Estado de la orden"; smtp.Host = "smtp.gmail.com"; smtp.Port = 587; smtp.Credentials = new NetworkCredential(from, password); smtp.EnableSsl = true; string text = "Aprobacion plantilla desde .net y sugerencias"; AlternateView plainView = AlternateView.CreateAlternateViewFromString(text, Encoding.UTF8, MediaTypeNames.Text.Plain); string html = templateBody(customer); AlternateView htmlView = AlternateView.CreateAlternateViewFromString(html, Encoding.UTF8, MediaTypeNames.Text.Html); LinkedResource img = new LinkedResource(@"C:\touresBalon.jpg", MediaTypeNames.Image.Jpeg); img.ContentId = "imagen"; htmlView.LinkedResources.Add(img); m.AlternateViews.Add(plainView); m.AlternateViews.Add(htmlView); m.IsBodyHtml = true; smtp.Send(m); return true; } catch (Exception e) { Console.WriteLine(e.StackTrace); return false; } }
public void SendMail(string from_Email, string to_Email, string CCList, string body, string from_Name, string Subject, string imagePath,string bodyImagePath) { try { MailMessage mail = new MailMessage(); mail.IsBodyHtml = true; AlternateView htmlView = AlternateView.CreateAlternateViewFromString(body, null, "text/html"); LinkedResource theEmailImage = new LinkedResource(imagePath); theEmailImage.ContentId = "myImageID"; LinkedResource theBodyImage = new LinkedResource(bodyImagePath); theBodyImage.ContentId = "myBodyId"; htmlView.LinkedResources.Add(theEmailImage); htmlView.LinkedResources.Add(theBodyImage); mail.AlternateViews.Add(htmlView); mail.From = new MailAddress(from_Email, from_Name); mail.To.Add(to_Email); mail.CC.Add(CCList); mail.Subject = Subject; System.Net.NetworkCredential cred = new System.Net.NetworkCredential(fromEmailIdStr, password); SmtpClient smtp = new SmtpClient(mailServerName, port); smtp.EnableSsl = true; smtp.DeliveryMethod = SmtpDeliveryMethod.Network; smtp.UseDefaultCredentials = false; smtp.Credentials = cred; smtp.Send(mail); } catch (Exception ex) { ExceptionLogger log = new ExceptionLogger(); log.DoLog(ex); } }
public void Send(string subject, string body,Dictionary<string, string> images) { if(string.IsNullOrEmpty(_smtpHost)) throw new InvalidOperationException("Невозможно отправить сообщение - не указан smtpHost"); if (string.IsNullOrEmpty(_smtpUserName)) throw new InvalidOperationException("Невозможно отправить сообщение - не указан smtpUserName"); if (string.IsNullOrEmpty(_smtpPassword)) throw new InvalidOperationException("Невозможно отправить сообщение - не указан smtpPassword"); if (string.IsNullOrEmpty(_from)) throw new InvalidOperationException("Невозможно отправить сообщение - не указан from"); if (string.IsNullOrEmpty(_to)) throw new ArgumentNullException("to"); string[] recipients = _to.Split(';'); foreach (string recipient in recipients) { if (string.IsNullOrEmpty(recipient.Trim())) continue; MailMessage mess = new MailMessage(_from, recipient); mess.Subject = subject; AlternateView htmlView = AlternateView.CreateAlternateViewFromString(body.Replace(Environment.NewLine,"</br>"), null, "text/html"); AlternateView plainView = AlternateView.CreateAlternateViewFromString(body, null, "text/plain"); //create the LinkedResource (embedded image) foreach (string key in images.Keys) { string fileName = images[key]; LinkedResource logo = new LinkedResource(fileName); logo.ContentId = key; //add the LinkedResource to the appropriate view htmlView.LinkedResources.Add(logo); } mess.AlternateViews.Add(plainView); mess.AlternateViews.Add(htmlView); SmtpClient client = new SmtpClient(_smtpHost,587); System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(_smtpUserName, _smtpPassword); client.UseDefaultCredentials = false; client.EnableSsl = true; client.Credentials = SMTPUserInfo; client.Send(mess); } }
/// <summary> /// Sends follow-up email to Library patron /// </summary> /// <param name="username">Bucknell username of patron</param> /// <param name="pub">Pulication instance to follow up</param> public static async void emailSend(string username, Publication pub) { var fromAddress = new MailAddress(Properties.Settings.Default.MailFrom, Properties.Settings.Default.MailName); MailAddress toAddress; try { toAddress = new MailAddress(username + "@bucknell.edu", await getFullName(username)); } catch (Exception) { Console.WriteLine("Invalid username. Email not sent."); return; } string fromPassword = Properties.Settings.Default.MailPassword; string subject = "Here is your eBook!: " + pub.Title; MemoryStream str = new MemoryStream(); PngBitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(pub.CoverImage)); encoder.Save(str); str.Position = 0; var coverInline = new LinkedResource(str, "image/png"); string body = getMessageBody(await getFirstName(username), pub, coverInline); var smtp = new SmtpClient { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(fromAddress.Address, fromPassword) }; using (var message = new MailMessage(fromAddress, toAddress) { Subject = subject, Body = body, IsBodyHtml = true }) { try { var view = AlternateView.CreateAlternateViewFromString(body, null, "text/html"); view.LinkedResources.Add(coverInline); message.AlternateViews.Add(view); await smtp.SendMailAsync(message); Console.WriteLine("Sent to " + toAddress); } catch (Exception e) { Console.WriteLine("Error: " + e); } } }
public IHttpActionResult SendEmail(bool isDigest) { var addresses = new List<string>(); addresses.Add("*****@*****.**"); MailMessage mail = new MailMessage(); mail.From = new MailAddress("*****@*****.**"); foreach (var address in addresses) { mail.To.Add(address); } IEmailBodyBuilder builder; if (isDigest) { mail.Subject = "Cadre Digest Email"; builder = new DigestBodyBuilder(); } else { mail.Subject = "Cadre Reminder Email"; builder = new ReminderBodyBuilder(); } var vmBuilder = new PostViewModelBuilder(database); mail.Body = builder.Build(vmBuilder.Build(database.Get<Post>())); AlternateView htmlView = AlternateView.CreateAlternateViewFromString( mail.Body, null, "text/html"); LinkedResource logo = new LinkedResource( "C:/Users/Cameron/Documents/Visual Studio 2015/Projects/Cadre/Cadre/Content/logo_long.png"); logo.ContentId = "companylogo"; htmlView.LinkedResources.Add(logo); mail.AlternateViews.Add(htmlView); mail.IsBodyHtml = true; SendSmtpEmail(mail); return Ok(); }
public void SaveHtmlWithImage() { MailMessage testMail = new MailMessage(); testMail.To.Add(new MailAddress("*****@*****.**")); testMail.From = new MailAddress("*****@*****.**"); testMail.Subject = "I am subject"; String htmlBody = "<img src=\"cid:uniqueId\" />"; AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html); htmlView.TransferEncoding = System.Net.Mime.TransferEncoding.SevenBit; LinkedResource image = new LinkedResource(@"c:\temp\Ascent.jpg"); image.ContentId = "uniqueId"; htmlView.LinkedResources.Add(image); testMail.AlternateViews.Add(htmlView); testMail.Save(@"c:\Temp\testemail.eml"); }
public ImageAttachBuilder DownloadAndAttachImage(string urlImage, string imageResourceContentId) { string localFilename = Path.GetTempFileName(); using (WebClient client = new WebClient()) { client.DownloadFile(urlImage, localFilename); } System.Net.Mail.LinkedResource imageResource = new System.Net.Mail.LinkedResource(localFilename, "image/jpg"); imageResource.ContentId = imageResourceContentId; _linkedResources.Add(imageResource); ImageAttachBuilder imageAttachBuilder = new ImageAttachBuilder(this, _modelloHtml, imageResourceContentId); return(imageAttachBuilder); }
public void SendNotification(string[] addresses, string title, string htmlMessage, LinkedResource linkedResource, bool useBcc) { using (AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlMessage, Encoding.UTF8, "text/html")) { if (linkedResource != null) { htmlView.LinkedResources.Add(linkedResource); } using (MailMessage mailMessage = new MailMessage()) { mailMessage.Subject = title; mailMessage.From = new MailAddress(this.senderAddress); if (useBcc) { mailMessage.To.Add(this.senderAddress); foreach (var email in addresses) { mailMessage.Bcc.Add(email); } } else { foreach (var email in addresses) { mailMessage.To.Add(email); } } mailMessage.AlternateViews.Add(htmlView); using (var smtpClient = new SmtpClient(this.smtpHost, this.smtpPort)) { smtpClient.EnableSsl = true; smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; smtpClient.Credentials = new NetworkCredential(this.smtpUser, this.smtpPassword); smtpClient.Send(mailMessage); } } } }
public void Test_GetAll_should_call_get_and_add_to_list() { var linkedResourceProvider = new Mock<LinkedResourceProvider> { CallBase = true }; var logo = new LinkedResource(new MemoryStream()); var banner = new LinkedResource(new MemoryStream()); linkedResourceProvider.Setup(p => p.Get("logo", "logo.png")).Returns(logo); linkedResourceProvider.Setup(p => p.Get("banner", "banner.png")).Returns(banner); var resourcesMap = new Dictionary<string, string>(){ {"logo", "logo.png"}, {"banner", "banner.png"} }; var resources = linkedResourceProvider.Object.GetAll(resourcesMap); linkedResourceProvider.VerifyAll(); Assert.AreEqual(logo, resources.First()); Assert.AreEqual(banner, resources.Last()); }
public static bool SendC2CMail(string _body, string _subject, string _from, string _to, MemoryStream _pdfstream, string _fname) { MailMessage msg = new MailMessage(); msg.BodyEncoding = UTF8Encoding.UTF8; msg.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure; if (string.IsNullOrEmpty(_from)) _from = "*****@*****.**"; msg.From = new MailAddress(_from); msg.To.Add(_to); msg.IsBodyHtml = true; msg.Body = Regex.Replace(_body, Environment.NewLine, "<br/>"); msg.Subject = _subject; var client = new SmtpClient("smtp.gmail.com", 587) { UseDefaultCredentials = false, Credentials = new NetworkCredential("*****@*****.**", "Campus2Caretaker@2015"), EnableSsl = true, Timeout = 10000, DeliveryMethod = SmtpDeliveryMethod.Network, }; StringBuilder sbBody = new StringBuilder(); var inlineLogo = new LinkedResource(HttpContext.Current.Server.MapPath(@"~\images\newlogo.png")); inlineLogo.ContentId = Guid.NewGuid().ToString(); sbBody.Append(string.Format("<img src='cid:{0}' /><br/><br/>", inlineLogo.ContentId)); sbBody.Append(msg.Body); sbBody.AppendLine("<br/>"); sbBody.AppendLine("*****************************DISCLAIMER*****************************"); sbBody.AppendLine("<br/>"); sbBody.AppendLine("Some copy right information here..."); var view = AlternateView.CreateAlternateViewFromString(sbBody.ToString(), null, "text/html"); //view.LinkedResources.Add(inlineLogo); msg.AlternateViews.Add(view); //System.IO.File.AppendAllText(@"E:\sam.txt", "READY FOR SENDING " + DateTime.Now.ToString() + Environment.NewLine); client.Send(msg); return true; }
internal static LinkedResourceWrapper GetLinkedResourceWrapper(LinkedResource lr) { if (lr == null) return null; LinkedResourceWrapper slr = new LinkedResourceWrapper(); slr._contentId = lr.ContentId; slr._contentLink = lr.ContentLink; if (lr.ContentStream != null) { byte[] bytes = new byte[lr.ContentStream.Length]; lr.ContentStream.Read(bytes, 0, bytes.Length); slr._contentStream = new MemoryStream(bytes); } slr._contentType = ContentTypeWrapper.GetSerializeableContentType(lr.ContentType); slr._transferEncoding = lr.TransferEncoding; return slr; }
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 Task SendAsync(string from, string to, string message) { SmtpClient smtp = new SmtpClient(); MailMessage mail = new MailMessage(); mail.From = new MailAddress(from); mail.To.Add(new MailAddress(to)); mail.Subject = "Inquiry"; string body = string.Format("<html><body><table>{0}<tr><td><br />Thank you for using the © Locarno Sun Dried Fruit platform</td></tr><tr><td><br /><img src=cid:LogoImage></td></tr></table></body></html>", message); AlternateView htmlView = AlternateView.CreateAlternateViewFromString(body.Trim(), null, "text/html"); string fileNameLogo = HttpContext.Current.Server.MapPath("~/Content/Images/Logopng.png"); System.Net.Mail.LinkedResource imageResource = new System.Net.Mail.LinkedResource(fileNameLogo, "image/png"); imageResource.ContentId = "LogoImage"; htmlView.LinkedResources.Add(imageResource); mail.AlternateViews.Add(htmlView); smtp.Send(mail); return(Task.FromResult(0)); }
protected void sendMailToEmployee(string subject, string body, string mail) { using (MailMessage mm = new MailMessage("*****@*****.**", mail)) { try { mm.Subject = subject; string str = @"<html><body>" + body + "<br /><img src=\"cid:image1\"></body></html>"; AlternateView av = System.Net.Mail.AlternateView.CreateAlternateViewFromString(str, null, System.Net.Mime.MediaTypeNames.Text.Html); LinkedResource lr = new System.Net.Mail.LinkedResource("images/logo1.png", MediaTypeNames.Image.Jpeg); lr.ContentId = "image1"; av.LinkedResources.Add(lr); mm.AlternateViews.Add(av); mm.IsBodyHtml = true; SmtpClient smtp = new SmtpClient(); smtp.Host = "smtp.gmail.com"; smtp.EnableSsl = true; NetworkCredential NetworkCred = new NetworkCredential("*****@*****.**", "jdzydiyrrvfnrjbf"); smtp.UseDefaultCredentials = true; smtp.Credentials = NetworkCred; smtp.Port = 587; smtp.Send(mm); alertmod.Style.Add("background-color", "#d7ecc6"); alert.Style.Add("background-color", "#d7ecc6"); Label3.ForeColor = System.Drawing.ColorTranslator.FromHtml("green"); Label5.ForeColor = System.Drawing.ColorTranslator.FromHtml("black"); Label3.Text = "Success!"; Label5.Text = "Employee promoted as an approver"; alert.Visible = true; } catch (Exception ex) { Response.Write(ex.Message); } } }
protected void btnSubmit_Click(object sender, EventArgs e) { advisorVo = (AdvisorVo)Session["advisorVo"]; if (Session["AdvisorPreferenceVo"] != null) { advisorPreferenceVo = (AdvisorPreferenceVo)Session["AdvisorPreferenceVo"]; } // userVo = userBo.GetUser(txtLoginId.Text); userVo = userBo.GetUserReset(txtLoginId.Text, txtEmail.Text, TxtPan.Text); if (userVo != null) { advisorVo = advisorBo.GetAssociateAdviserUser(userVo.UserId); } Random r = new Random(); OneWayEncryption encryption; encryption = new OneWayEncryption(); bool isSuccess = false; string logoPath = string.Empty; string statusMessage = string.Empty; ScriptManager script = new ScriptManager(); if (userVo != null) // && userVo.Email == txtEmail.Text ) { string hassedPassword = string.Empty; string saltValue = string.Empty; string password = r.Next(20000, 100000).ToString(); //userVo = userBo.GetUserDetails(userId); // string userName = userVo.FirstName + " " + userVo.MiddleName + " " + userVo.LastName; encryption.GetHashAndSaltString(password, out hassedPassword, out saltValue); userVo.Password = hassedPassword; userVo.PasswordSaltValue = saltValue; userVo.OriginalPassword = password; userVo.IsTempPassword = 1; // isSuccess = userBo.UpdateUser(userVo); isSuccess = userBo.UpdateUserReset(userVo); string userName = userVo.FirstName + " " + userVo.MiddleName + " " + userVo.LastName; email.GetResetPasswordMail(userVo.LoginId, password, userName); email.Subject = email.Subject.Replace("WealthERP", advisorVo.OrganizationName); email.Subject = email.Subject.Replace("MoneyTouch", advisorVo.OrganizationName); //email.Body = email.Body.Replace("[ORGANIZATION]", advisorVo.OrganizationName); email.Body = email.Body.Replace("[CUSTOMER_NAME]", userVo.FirstName); if (ConfigurationSettings.AppSettings["HostName"].ToString() == "Wealtherp") { email.Body = email.Body.Replace("[WEBSITE]", advisorPreferenceVo.WebSiteDomainName); } else if (ConfigurationSettings.AppSettings["HostName"].ToString() == "Citrus") { email.Body = email.Body.Replace("[WEBSITE]", advisorPreferenceVo.WebSiteDomainName); } email.Body = email.Body.Replace("[CONTACTPERSON]", advisorVo.ContactPersonFirstName + " " + advisorVo.ContactPersonMiddleName + " " + advisorVo.ContactPersonLastName); if (!string.IsNullOrEmpty(advisorVo.Designation)) { email.Body = email.Body.Replace("[DESIGNATION]", advisorVo.Designation.Trim()); } else { email.Body = email.Body.Replace("[DESIGNATION]", string.Empty); } if (!string.IsNullOrEmpty(advisorVo.Phone1Number.ToString())) { email.Body = email.Body.Replace("[PHONE]", advisorVo.Phone1Std.ToString().Trim() + "-" + advisorVo.Phone1Number.ToString().Trim()); } else { email.Body = email.Body.Replace("[PHONE]", string.Empty); } if (!string.IsNullOrEmpty(advisorVo.Email)) { email.Body = email.Body.Replace("[EMAIL]", advisorVo.Email.Trim()); } else { email.Body = email.Body.Replace("[EMAIL]", string.Empty); } email.Body = email.Body.Replace("[LOGO]", "<img src='cid:HDIImage' alt='Logo'>"); System.Net.Mail.AlternateView htmlView; System.Net.Mail.AlternateView plainTextView = System.Net.Mail.AlternateView.CreateAlternateViewFromString("Text view", null, "text/plain"); //System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(hidBody.Value.Trim() + "<image src=cid:HDIImage>", null, "text/html"); htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString("<html><body " + "style='font-family:Tahoma, Arial; font-size: 10pt;'><p>" + email.Body + "</p></body></html>", null, "text/html"); //Add image to HTML version if (advisorVo != null) { logoPath = "~/Images/" + advisorVo.LogoPath; } if (!File.Exists(Server.MapPath(logoPath))) { logoPath = "~/Images/spacer.png"; } //System.Net.Mail.LinkedResource imageResource = new System.Net.Mail.LinkedResource(Server.MapPath("~/Images/") + @"\3DSYRW_4009.JPG", "image/jpeg"); System.Net.Mail.LinkedResource imageResource = new System.Net.Mail.LinkedResource(Server.MapPath(logoPath), "image/jpeg"); imageResource.ContentId = "HDIImage"; htmlView.LinkedResources.Add(imageResource); //Add two views to message. email.AlternateViews.Add(plainTextView); email.AlternateViews.Add(htmlView); email.To.Add(userVo.Email); AdviserStaffSMTPBo adviserStaffSMTPBo = new AdviserStaffSMTPBo(); int rmId = userVo.rmid; AdviserStaffSMTPVo adviserStaffSMTPVo = adviserStaffSMTPBo.GetSMTPCredentials(rmId); if (adviserStaffSMTPVo.HostServer != null && adviserStaffSMTPVo.HostServer != string.Empty) { emailer.isDefaultCredentials = !Convert.ToBoolean(adviserStaffSMTPVo.IsAuthenticationRequired); if (!String.IsNullOrEmpty(adviserStaffSMTPVo.Password)) { emailer.smtpPassword = Encryption.Decrypt(adviserStaffSMTPVo.Password); } emailer.smtpPort = int.Parse(adviserStaffSMTPVo.Port); emailer.smtpServer = adviserStaffSMTPVo.HostServer; emailer.smtpUserName = adviserStaffSMTPVo.Email; if (Convert.ToBoolean(adviserStaffSMTPVo.IsAuthenticationRequired)) { if (ConfigurationSettings.AppSettings["HostName"].ToString() == "Wealtherp") { email.From = new MailAddress(emailer.smtpUserName, advisorVo.OrganizationName); } else if (ConfigurationSettings.AppSettings["HostName"].ToString() == "MoneyTouch") { email.From = new MailAddress(emailer.smtpUserName, advisorVo.OrganizationName); } } } bool isMailSent = false; if (userBo.UpdateUser(userVo)) { isMailSent = emailer.SendMail(email); } if (isMailSent) { statusMessage = "Credentials have been reset and sent to your mail"; tblMessage.Visible = true; ErrorMessage.Visible = false; SuccessMsg.InnerText = statusMessage; SuccessMsg.Visible = true; txtLoginId.Text = ""; txtEmail.Text = ""; TxtPan.Text = ""; } } else { statusMessage = "Password has been not reset sucessfully"; tblMessage.Visible = true; ErrorMessage.Visible = true; ErrorMessage.InnerText = statusMessage; SuccessMsg.Visible = false; txtLoginId.Text = ""; txtEmail.Text = ""; TxtPan.Text = ""; } //if (isSuccess) //{ // tblMessage.Visible = true; // SuccessMsg.Visible = true; // ErrorMessage.Visible = false; // SuccessMsg.InnerText = "Password has been reset successfully..."; // txtLoginId.Text = ""; // txtEmail.Text = ""; // TxtPan.Text = ""; //} //else //{ // tblMessage.Visible = true; // SuccessMsg.Visible = false; // ErrorMessage.Visible = true; // ErrorMessage.InnerText = "An error occurred while reseting password."; //} }
protected void btnGenerate_Click(object sender, EventArgs e) { AdvisorPreferenceVo advisorPreferenceVo = new AdvisorPreferenceVo(); advisorVo = (AdvisorVo)Session["advisorVo"]; if (Session["AdvisorPreferenceVo"] != null) { advisorPreferenceVo = (AdvisorPreferenceVo)Session["AdvisorPreferenceVo"]; } int selectedRecords = 0; string statusMessage = string.Empty; advisorVo = (AdvisorVo)Session["advisorVo"]; string logoPath = string.Empty; if (Page.IsValid) { //Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "leftpane", "$.colorbox({width: '700px', overlayClose: false, inline: true, href: '#LoadImage'});", true); try { foreach (GridDataItem gvr in gvUserMgt.Items) { if (((CheckBox)gvr.FindControl("cbRecons")).Checked == true) { selectedRecords++; int selectedRow = gvr.ItemIndex + 1; string Phone1Details = string.Empty, phone2Details = string.Empty, phone3Details = string.Empty, PhoneNumber = string.Empty; userId = int.Parse((gvUserMgt.MasterTableView.DataKeyValues[selectedRow - 1]["UserId"].ToString())); Emailer emailer = new Emailer(); EmailMessage email = new EmailMessage(); string hassedPassword = string.Empty; string saltValue = string.Empty; encryption = new OneWayEncryption(); Random r = new Random(); userVo = userBo.GetUserDetails(userId); string password = r.Next(20000, 100000).ToString(); encryption.GetHashAndSaltString(password, out hassedPassword, out saltValue); userVo.Password = hassedPassword; userVo.PasswordSaltValue = saltValue; userVo.OriginalPassword = password; userVo.IsTempPassword = 1; userBo.UpdateUser(userVo); string userName = userVo.FirstName + " " + userVo.MiddleName + " " + userVo.LastName; email.GetResetPasswordMail(userVo.LoginId, password, userName); email.Subject = email.Subject.Replace("WealthERP", advisorVo.OrganizationName); email.Subject = email.Subject.Replace("MoneyTouch", advisorVo.OrganizationName); //email.Body = email.Body.Replace("[ORGANIZATION]", advisorVo.OrganizationName); email.Body = email.Body.Replace("[CUSTOMER_NAME]", userVo.FirstName); if (ConfigurationSettings.AppSettings["HostName"].ToString() == "Wealtherp") { email.Body = email.Body.Replace("[WEBSITE]", advisorPreferenceVo.WebSiteDomainName); } else if (ConfigurationSettings.AppSettings["HostName"].ToString() == "Citrus") { email.Body = email.Body.Replace("[WEBSITE]", advisorPreferenceVo.WebSiteDomainName); } email.Body = email.Body.Replace("[CONTACTPERSON]", advisorVo.ContactPersonFirstName + " " + advisorVo.ContactPersonMiddleName + " " + advisorVo.ContactPersonLastName); if (!string.IsNullOrEmpty(advisorVo.Designation)) { email.Body = email.Body.Replace("[DESIGNATION]", advisorVo.Designation.Trim()); } else { email.Body = email.Body.Replace("[DESIGNATION]", string.Empty); } if (!string.IsNullOrEmpty(advisorVo.Phone1Number.ToString()) || !string.IsNullOrEmpty(advisorVo.Phone2Number.ToString()) || !string.IsNullOrEmpty(advisorVo.Phone3Number.ToString())) { if (!string.IsNullOrEmpty(advisorVo.Phone1Isd) && !string.IsNullOrEmpty(advisorVo.Phone1Std) && advisorVo.Phone1Number > 1) { Phone1Details = advisorVo.Phone1Isd.ToString() + "-" + advisorVo.Phone1Std.ToString() + "-" + advisorVo.Phone1Number.ToString(); } else if (!string.IsNullOrEmpty(advisorVo.Phone1Isd) && !string.IsNullOrEmpty(advisorVo.Phone1Std) && advisorVo.Phone1Number > 1) { Phone1Details = advisorVo.Phone1Std.ToString() + "-" + advisorVo.Phone1Number.ToString(); } else if (!string.IsNullOrEmpty(advisorVo.Phone1Isd) && !string.IsNullOrEmpty(advisorVo.Phone1Std) && advisorVo.Phone1Number > 1) { Phone1Details = advisorVo.Phone1Isd.ToString() + "-" + advisorVo.Phone1Number.ToString(); } else if (string.IsNullOrEmpty(advisorVo.Phone1Isd) && string.IsNullOrEmpty(advisorVo.Phone1Std) && advisorVo.Phone1Number > 1) { Phone1Details = advisorVo.Phone1Number.ToString(); } if (!string.IsNullOrEmpty(advisorVo.Phone2Isd) && !string.IsNullOrEmpty(advisorVo.Phone2Std) && advisorVo.Phone2Number > 1) { phone2Details = advisorVo.Phone2Isd.ToString() + "-" + advisorVo.Phone2Std.ToString() + "-" + advisorVo.Phone2Number.ToString(); } else if (string.IsNullOrEmpty(advisorVo.Phone2Isd) && !string.IsNullOrEmpty(advisorVo.Phone2Std) && advisorVo.Phone2Number > 1) { phone2Details = advisorVo.Phone2Std.ToString() + "-" + advisorVo.Phone2Number.ToString(); } else if (!string.IsNullOrEmpty(advisorVo.Phone2Isd) && string.IsNullOrEmpty(advisorVo.Phone2Std) && advisorVo.Phone2Number > 1) { phone2Details = advisorVo.Phone2Isd.ToString() + "-" + advisorVo.Phone2Number.ToString(); } else if (string.IsNullOrEmpty(advisorVo.Phone2Isd) && string.IsNullOrEmpty(advisorVo.Phone2Std) && advisorVo.Phone2Number > 1) { phone2Details = advisorVo.Phone2Number.ToString(); } if (!string.IsNullOrEmpty(advisorVo.Phone3Isd) && !string.IsNullOrEmpty(advisorVo.Phone3Std) && advisorVo.Phone3Number > 1) { phone3Details = advisorVo.Phone3Isd.ToString() + "-" + advisorVo.Phone3Std.ToString() + "-" + advisorVo.Phone3Number.ToString(); } else if (string.IsNullOrEmpty(advisorVo.Phone3Isd) && !string.IsNullOrEmpty(advisorVo.Phone3Std) && advisorVo.Phone3Number > 1) { phone3Details = advisorVo.Phone3Std.ToString() + "-" + advisorVo.Phone3Number.ToString(); } else if (!string.IsNullOrEmpty(advisorVo.Phone3Isd) && string.IsNullOrEmpty(advisorVo.Phone3Std) && advisorVo.Phone3Number > 1) { phone3Details = advisorVo.Phone3Isd.ToString() + "-" + advisorVo.Phone3Number.ToString(); } else if (string.IsNullOrEmpty(advisorVo.Phone3Isd) && string.IsNullOrEmpty(advisorVo.Phone3Std) && advisorVo.Phone3Number > 1) { phone3Details = advisorVo.Phone3Number.ToString(); } if (!string.IsNullOrEmpty(Phone1Details) && !string.IsNullOrEmpty(phone2Details) && !string.IsNullOrEmpty(phone3Details)) { PhoneNumber = Phone1Details + "/" + phone2Details + "/" + phone3Details; } else if (!string.IsNullOrEmpty(Phone1Details) && !string.IsNullOrEmpty(phone2Details) && string.IsNullOrEmpty(phone3Details)) { PhoneNumber = Phone1Details + "/" + phone2Details; } else if (string.IsNullOrEmpty(Phone1Details) && !string.IsNullOrEmpty(phone2Details) && !string.IsNullOrEmpty(phone3Details)) { PhoneNumber = phone2Details + "/" + phone3Details; } else if (!string.IsNullOrEmpty(Phone1Details) && string.IsNullOrEmpty(phone2Details) && !string.IsNullOrEmpty(phone3Details)) { PhoneNumber = Phone1Details + "/" + phone3Details; } else if (!string.IsNullOrEmpty(Phone1Details) && string.IsNullOrEmpty(phone2Details) && string.IsNullOrEmpty(phone3Details)) { PhoneNumber = Phone1Details; } else if (string.IsNullOrEmpty(Phone1Details) && !string.IsNullOrEmpty(phone2Details) && string.IsNullOrEmpty(phone3Details)) { PhoneNumber = phone2Details; } else if (string.IsNullOrEmpty(Phone1Details) && string.IsNullOrEmpty(phone2Details) && !string.IsNullOrEmpty(phone3Details)) { PhoneNumber = phone3Details; } email.Body = email.Body.Replace("[PHONE]", PhoneNumber); } else { email.Body = email.Body.Replace("[PHONE]", string.Empty); } if (!string.IsNullOrEmpty(advisorVo.Email)) { email.Body = email.Body.Replace("[EMAIL]", advisorVo.Email.Trim()); } else { email.Body = email.Body.Replace("[EMAIL]", string.Empty); } email.Body = email.Body.Replace("[LOGO]", "<img src='cid:HDIImage' alt='Logo'>"); System.Net.Mail.AlternateView htmlView; System.Net.Mail.AlternateView plainTextView = System.Net.Mail.AlternateView.CreateAlternateViewFromString("Text view", null, "text/plain"); //System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(hidBody.Value.Trim() + "<image src=cid:HDIImage>", null, "text/html"); htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString("<html><body " + "style='font-family:Tahoma, Arial; font-size: 10pt;'><p>" + email.Body + "</p></body></html>", null, "text/html"); //Add image to HTML version if (advisorVo != null) { logoPath = "~/Images/" + advisorVo.LogoPath; } if (!File.Exists(Server.MapPath(logoPath))) { logoPath = "~/Images/spacer.png"; } //System.Net.Mail.LinkedResource imageResource = new System.Net.Mail.LinkedResource(Server.MapPath("~/Images/") + @"\3DSYRW_4009.JPG", "image/jpeg"); System.Net.Mail.LinkedResource imageResource = new System.Net.Mail.LinkedResource(Server.MapPath(logoPath), "image/jpeg"); imageResource.ContentId = "HDIImage"; htmlView.LinkedResources.Add(imageResource); //Add two views to message. email.AlternateViews.Add(plainTextView); email.AlternateViews.Add(htmlView); email.To.Add(userVo.Email); AdviserStaffSMTPBo adviserStaffSMTPBo = new AdviserStaffSMTPBo(); int rmId = Convert.ToInt32(ViewState["rmId"]); AdviserStaffSMTPVo adviserStaffSMTPVo = adviserStaffSMTPBo.GetSMTPCredentials(rmId); if (adviserStaffSMTPVo.HostServer != null && adviserStaffSMTPVo.HostServer != string.Empty) { emailer.isDefaultCredentials = !Convert.ToBoolean(adviserStaffSMTPVo.IsAuthenticationRequired); if (!String.IsNullOrEmpty(adviserStaffSMTPVo.Password)) { emailer.smtpPassword = Encryption.Decrypt(adviserStaffSMTPVo.Password); } emailer.smtpPort = int.Parse(adviserStaffSMTPVo.Port); emailer.smtpServer = adviserStaffSMTPVo.HostServer; emailer.smtpUserName = adviserStaffSMTPVo.Email; if (Convert.ToBoolean(adviserStaffSMTPVo.IsAuthenticationRequired)) { if (ConfigurationSettings.AppSettings["HostName"].ToString() == "Wealtherp") { email.From = new MailAddress(emailer.smtpUserName, advisorVo.OrganizationName); } else if (ConfigurationSettings.AppSettings["HostName"].ToString() == "MoneyTouch") { email.From = new MailAddress(emailer.smtpUserName, advisorVo.OrganizationName); } } } bool isMailSent = false; if (userBo.UpdateUser(userVo)) { isMailSent = emailer.SendMail(email); } if (isMailSent) { statusMessage = "Credentials have been reset and sent to selected user"; tblMessage.Visible = true; ErrorMessage.Visible = false; SuccessMsg.InnerText = statusMessage; SuccessMsg.Visible = true; } else { statusMessage = "An error occurred while sending mail to selected user"; tblMessage.Visible = true; ErrorMessage.Visible = true; ErrorMessage.InnerText = statusMessage; SuccessMsg.Visible = false; } } } //if (selectedRecords == 0) //statusMessage = "Please select RM to send Password"; ErrorMessage.Visible = false; } catch (BaseApplicationException Ex) { throw Ex; } catch (Exception Ex) { BaseApplicationException exBase = new BaseApplicationException(Ex.Message, Ex); NameValueCollection FunctionInfo = new NameValueCollection(); FunctionInfo.Add("Method", "RMCustomerUserDetails.ascx:btnGenerate_Click()"); exBase.AdditionalInformation = FunctionInfo; ExceptionManager.Publish(exBase); throw exBase; } } }
private bool SendMail(UserVo userVo, bool isNewLogin) { Emailer emailer = new Emailer(); EmailMessage email = new EmailMessage(); AdvisorPreferenceVo advisorPreferenceVo = new AdvisorPreferenceVo(); advisorVo = (AdvisorVo)Session["advisorVo"]; if (Session["AdvisorPreferenceVo"] != null) { advisorPreferenceVo = (AdvisorPreferenceVo)Session["AdvisorPreferenceVo"]; } string logoPath = string.Empty; bool isMailSent = false; bool isEmailIdBlank = false; try { UserVo uservo = (UserVo)Session["userVo"]; AdvisorStaffBo adviserstaffbo = new AdvisorStaffBo(); //Get SMTP settings of admin if configured. RMVo advrm = new RMVo(); advrm = adviserstaffbo.GetAdvisorStaff(uservo.UserId); AdviserStaffSMTPBo adviserStaffSMTPBo = new AdviserStaffSMTPBo(); AdviserStaffSMTPVo adviserStaffSMTPVo = adviserStaffSMTPBo.GetSMTPCredentials(advrm.RMId); //Get the mail contents if (userVo.Email.Trim() != string.Empty) { email.To.Add(userVo.Email); string name = userVo.FirstName + " " + userVo.MiddleName + " " + userVo.LastName; if (isNewLogin) { email.GetCustomerAccountMail(userVo.LoginId, userVo.OriginalPassword, name); } else { email.GetResetPasswordMail(userVo.LoginId, userVo.OriginalPassword, name); } email.Subject = email.Subject.Replace("WealthERP", advisorVo.OrganizationName); email.Subject = email.Subject.Replace("MoneyTouch", advisorVo.OrganizationName); email.Body = email.Body.Replace("[ORGANIZATION]", advisorVo.OrganizationName); email.Body = email.Body.Replace("[CUSTOMER_NAME]", userVo.FirstName); if (ConfigurationSettings.AppSettings["HostName"].ToString() == "Wealtherp") { email.Body = email.Body.Replace("[WEBSITE]", advisorPreferenceVo.WebSiteDomainName); } else if (ConfigurationSettings.AppSettings["HostName"].ToString() == "Citrus") { email.Body = email.Body.Replace("[WEBSITE]", advisorPreferenceVo.WebSiteDomainName); } email.Body = email.Body.Replace("[CONTACTPERSON]", advisorVo.ContactPersonFirstName + " " + advisorVo.ContactPersonMiddleName + " " + advisorVo.ContactPersonLastName); if (!string.IsNullOrEmpty(advisorVo.Designation)) { email.Body = email.Body.Replace("[DESIGNATION]", advisorVo.Designation); } else { email.Body = email.Body.Replace("[DESIGNATION]", string.Empty); } if (!string.IsNullOrEmpty(advisorVo.Phone1Number.ToString())) { email.Body = email.Body.Replace("[PHONE]", advisorVo.Phone1Std.ToString() + "-" + advisorVo.Phone1Number.ToString()); } else { email.Body = email.Body.Replace("[PHONE]", string.Empty); } if (!string.IsNullOrEmpty(advisorVo.Email)) { email.Body = email.Body.Replace("[EMAIL]", advisorVo.Email); } else { email.Body = email.Body.Replace("[EMAIL]", string.Empty); } email.Body = email.Body.Replace("[LOGO]", "<img src='cid:HDIImage' alt='Logo'>"); System.Net.Mail.AlternateView htmlView; System.Net.Mail.AlternateView plainTextView = System.Net.Mail.AlternateView.CreateAlternateViewFromString("Text view", null, "text/plain"); //System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(hidBody.Value.Trim() + "<image src=cid:HDIImage>", null, "text/html"); htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString("<html><body " + "style='font-family:Tahoma, Arial; font-size: 10pt;'><p>" + email.Body + "</p></body></html>", null, "text/html"); //Add image to HTML version if (advisorVo != null) { logoPath = "~/Images/" + advisorVo.LogoPath; } if (!File.Exists(Server.MapPath(logoPath))) { logoPath = "~/Images/spacer.png"; } //System.Net.Mail.LinkedResource imageResource = new System.Net.Mail.LinkedResource(Server.MapPath("~/Images/") + @"\3DSYRW_4009.JPG", "image/jpeg"); System.Net.Mail.LinkedResource imageResource = new System.Net.Mail.LinkedResource(Server.MapPath(logoPath), "image/jpeg"); imageResource.ContentId = "HDIImage"; htmlView.LinkedResources.Add(imageResource); //Add two views to message. email.AlternateViews.Add(plainTextView); email.AlternateViews.Add(htmlView); //Send message //System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(); //Assign SMTP Credentials if configured. if (adviserStaffSMTPVo.HostServer != null && adviserStaffSMTPVo.HostServer != string.Empty) { emailer.isDefaultCredentials = !Convert.ToBoolean(adviserStaffSMTPVo.IsAuthenticationRequired); if (!String.IsNullOrEmpty(adviserStaffSMTPVo.Password)) { emailer.smtpPassword = Encryption.Decrypt(adviserStaffSMTPVo.Password); } emailer.smtpPort = int.Parse(adviserStaffSMTPVo.Port); emailer.smtpServer = adviserStaffSMTPVo.HostServer; emailer.smtpUserName = adviserStaffSMTPVo.Email; if (Convert.ToBoolean(adviserStaffSMTPVo.IsAuthenticationRequired)) { if (ConfigurationSettings.AppSettings["HostName"].ToString() == "Wealtherp") { email.From = new MailAddress(emailer.smtpUserName, advisorVo.OrganizationName); } else if (ConfigurationSettings.AppSettings["HostName"].ToString() == "MoneyTouch") { email.From = new MailAddress(emailer.smtpUserName, advisorVo.OrganizationName); } } } //Sending mail... isMailSent = emailer.SendMail(email); } else { isEmailIdBlank = true; } if (isEmailIdBlank) { if (string.IsNullOrEmpty(statusMessage)) { statusMessage = "No email Id specified for selected User"; tblMessage.Visible = true; ErrorMessage.Visible = true; ErrorMessage.InnerText = statusMessage; SuccessMsg.Visible = false; } else { statusMessage = statusMessage + " and some selected User don't have E-mail id"; tblMessage.Visible = true; ErrorMessage.Visible = true; ErrorMessage.InnerText = statusMessage; SuccessMsg.Visible = false; } } else if (isMailSent) { if (string.IsNullOrEmpty(statusMessage)) { statusMessage = "Credentials have been sent to selected User"; tblMessage.Visible = true; ErrorMessage.Visible = false; SuccessMsg.InnerText = statusMessage; SuccessMsg.Visible = true; } else if (statusMessage == "No email Id specified for slected User") { statusMessage = "some selected User don't have E-mail id and Credentials have been sent sucessfully to rest of User"; statusMessage = "Credentials have been sent to selected User"; tblMessage.Visible = true; ErrorMessage.Visible = false; SuccessMsg.InnerText = statusMessage; SuccessMsg.Visible = true; } else { tblMessage.Visible = true; ErrorMessage.Visible = false; SuccessMsg.InnerText = statusMessage; SuccessMsg.Visible = true; } } else { statusMessage = "An error occurred while sending mail .. "; tblMessage.Visible = true; ErrorMessage.Visible = true; ErrorMessage.InnerText = statusMessage; SuccessMsg.Visible = false; } } catch (Exception ex) { } return(isMailSent); }
public static void SendMail(string To, string Cc, string Bcc, string Subject, string Body, ArrayList Attachments, string from, string emailTypeCode, DataTable dtAdviserSMTP, out string fromSMTPEmail, DataSet dsEmailTemplateDetails, out string statusMessage) { statusMessage = ""; fromSMTPEmail = ""; string templateId = string.Empty; string reportType = string.Empty; AdvisorPreferenceVo advisorPreferenceVo = null; AdvisorVo advisorVo = null; CustomerVo customerVo = null; RMVo rmVo = null; AdvisorBo advisorBo = new AdvisorBo(); CustomerBo customerBo = new CustomerBo(); AdvisorStaffBo advisorStaffBo = new AdvisorStaffBo(); AdviserPreferenceBo adviserPreferenceBo = new AdviserPreferenceBo(); DataTable dtEmailOutgoingParameterValues = dsEmailTemplateDetails.Tables[0]; DataTable dtEmailTemplateParameters = dsEmailTemplateDetails.Tables[1]; DataTable dtAdviserEmailTemplate = dsEmailTemplateDetails.Tables[2]; DataTable dtAdviserTemplateParametersPre = dsEmailTemplateDetails.Tables[3]; _SMTPFrom = from; SetAdviserSMTP(dtAdviserSMTP, _SMTPFrom); SmtpClient smtpClient = new SmtpClient(); EmailMessage email = new EmailMessage(); //MailMessage email = new MailMessage(_SMTPFromDisplay, To); _SMTPUsername = GetSMTPUserFromPool(); fromSMTPEmail = _SMTPUsername; email.To.Add(To); //string name = userVo.FirstName + " " + userVo.MiddleName + " " + userVo.LastName; email.ReadSendMailTemplate(emailTypeCode); foreach (DataRow dr in dtEmailOutgoingParameterValues.Rows) { switch (dr["WP_ParameterCode"].ToString()) { case "AID": advisorVo = advisorBo.GetAdvisor(Convert.ToInt32(dr["WRD_InputParameterValue"].ToString())); advisorPreferenceVo = adviserPreferenceBo.GetAdviserPreference(advisorVo.advisorId); break; case "CID": customerVo = customerBo.GetCustomer(Convert.ToInt32(dr["WRD_InputParameterValue"].ToString())); rmVo = advisorStaffBo.GetAdvisorStaffDetails(customerVo.RmId); break; case "RT": reportType = Convert.ToString(dr["WRD_InputParameterValue"]); break; } } foreach (DataRow dr in dtAdviserEmailTemplate.Rows) { if (dr["WERPTTM_TypeCode"].ToString() == emailTypeCode) { email.Body = email.Body.Replace("[EMAIL_BODY]", dr["AHTMLT_TemplateBody"].ToString()); templateId = dr["AHTMLT_Id"].ToString(); break; } } foreach (DataRow dr in dtEmailTemplateParameters.Rows) { string templateCode = dr["WERPTPM_TemplateParameterCode"].ToString(); switch (templateCode) { case "[ADVISER_NAME]": email.Body = email.Body.Replace(templateCode, advisorVo.FirstName + " " + advisorVo.MiddleName + " " + advisorVo.LastName); break; case "[ADVISER_PHONE]": email.Body = email.Body.Replace(templateCode, advisorVo.Phone1Std + "-" + advisorVo.Phone1Number); break; case "[ADVISER_MOBILE]": email.Body = email.Body.Replace(templateCode, advisorVo.MobileNumber.ToString()); break; case "[ADVISER_EMAIL]": email.Body = email.Body.Replace(templateCode, advisorVo.Email.ToString()); break; case "[A_WEB_SITE]": email.Body = email.Body.Replace(templateCode, advisorPreferenceVo.WebSiteDomainName.ToString()); break; case "[RM_NAME]": email.Body = email.Body.Replace(templateCode, rmVo.FirstName + " " + rmVo.MiddleName + " " + rmVo.LastName); break; case "[RM_MOBILE]": email.Body = email.Body.Replace(templateCode, rmVo.Mobile.ToString()); break; case "[RM_EMAIL]": email.Body = email.Body.Replace(templateCode, rmVo.Email.ToString()); break; case "[CUSTOMER_FIRST_NAME]": email.Body = email.Body.Replace(templateCode, customerVo.FirstName); break; case "[CUSTOMER_MIDDLE_NAME]": email.Body = email.Body.Replace(templateCode, customerVo.MiddleName); break; case "[CUSTOMER_LAST_NAME]": email.Body = email.Body.Replace(templateCode, customerVo.LastName); break; case "[START_LINE]": email.Body = email.Body.Replace(templateCode, "<font face=" + "\"" + "[TEXT_FONT_NAME]" + "\"" + " size=" + "\"" + "[TEXT_FONT_SIZE]" + "\"" + " color=" + "\"" + "[TEXT_COLOR]" + "\"" + ">"); break; case "[END_LINE]": email.Body = email.Body.Replace(templateCode, "</font>"); break; case "[LINE_BREAK]": email.Body = email.Body.Replace(templateCode, "<br />"); break; case "[ONE_EMPTY_SPACE]": email.Body = email.Body.Replace(templateCode, " "); break; case "[HYPERLINK_START]": email.Body = email.Body.Replace(templateCode, "<a href=" + "\"" + "[A_WEB_SITE]" + "\"" + "target=" + "\"" + "_blank" + "\"" + ">"); break; case "[HYPERLINK_END]": email.Body = email.Body.Replace(templateCode, "</a>"); break; case "[FONT_BOLD_START]": email.Body = email.Body.Replace(templateCode, "<b>"); break; case "[FONT_BOLD_END]": email.Body = email.Body.Replace(templateCode, "</b>"); break; case "[TEXT_FONT_NAME]": email.Body = email.Body.Replace(templateCode, GetTemplateParamerValue(dtAdviserTemplateParametersPre, templateId, dr["WERPTPM_ParameterCode"].ToString())); break; case "[TEXT_FONT_SIZE]": email.Body = email.Body.Replace(templateCode, GetTemplateParamerValue(dtAdviserTemplateParametersPre, templateId, dr["WERPTPM_ParameterCode"].ToString())); break; case "[TEXT_COLOR]": email.Body = email.Body.Replace(templateCode, GetTemplateParamerValue(dtAdviserTemplateParametersPre, templateId, dr["WERPTPM_ParameterCode"].ToString())); break; case "[REPORT_TYPE]": //string reportType = GetTemplateParamerValue(dtAdviserTemplateParametersPre, reportTypeCode, dr["WERPTPM_ParameterCode"].ToString()); email.Body = email.Body.Replace(templateCode, reportType); email.Subject = email.Subject.Replace(templateCode, reportType); break; } //email.Subject = email.Subject.Replace("MoneyTouch", advisorVo.OrganizationName); //email.Body = email.Body.Replace("[ORGANIZATION]", advisorVo.OrganizationName); //email.Body = email.Body.Replace("[CUSTOMER_NAME]", userVo.FirstName); //if (ConfigurationSettings.AppSettings["HostName"].ToString() == "Wealtherp") //{ // email.Body = email.Body.Replace("[WEBSITE]", advisorPreferenceVo.WebSiteDomainName); //} //else if (ConfigurationSettings.AppSettings["HostName"].ToString() == "Citrus") //{ // email.Body = email.Body.Replace("[WEBSITE]", advisorPreferenceVo.WebSiteDomainName); //} //email.Body = email.Body.Replace("[CONTACTPERSON]", advisorVo.ContactPersonFirstName + " " + advisorVo.ContactPersonMiddleName + " " + advisorVo.ContactPersonLastName); //if (!string.IsNullOrEmpty(advisorVo.Designation)) // email.Body = email.Body.Replace("[DESIGNATION]", advisorVo.Designation); //else // email.Body = email.Body.Replace("[DESIGNATION]", string.Empty); //if (!string.IsNullOrEmpty(advisorVo.Phone1Number.ToString())) // email.Body = email.Body.Replace("[PHONE]", advisorVo.Phone1Std.ToString() + "-" + advisorVo.Phone1Number.ToString()); //else // email.Body = email.Body.Replace("[PHONE]", string.Empty); //if (!string.IsNullOrEmpty(advisorVo.Email)) // email.Body = email.Body.Replace("[EMAIL]", advisorVo.Email); //else // email.Body = email.Body.Replace("[EMAIL]", string.Empty); //if (_SMTPDefaultCredentials == true) //{ // NetworkCredential basicCredential = new NetworkCredential(_SMTPUsername, _SMTPPassword); // smtpClient.UseDefaultCredentials = false; // smtpClient.Credentials = basicCredential; //} //else //{ // smtpClient.UseDefaultCredentials = true; //} //smtpClient.Host = _SMTPServer; //if (_SMTPPort > 0) // smtpClient.Port = _SMTPPort; ////Hardcoding SSL settings for gmail SMTP //if (_SMTPServer.Contains("smtp.gmail.com") || _SMTPServer.Contains("smtp.live.com")) //{ // smtpClient.EnableSsl = true; //} //if (Cc != null && Cc.Trim().Length > 0) // mail.CC.Add(Cc); //if (Bcc != null && Bcc.Trim().Length > 0) // mail.Bcc.Add(Bcc); //if (!string.IsNullOrEmpty(_SMTPFromDisplay.Trim())) //{ // if (_SMTPDefaultCredentials == true) // { // MailAddress md1 = new MailAddress(_SMTPUsername, _SMTPFromDisplay); // mail.From = md1; // } // if (!string.IsNullOrEmpty(from.Trim())) // { // MailAddress md3 = new MailAddress(_SMTPFrom, _SMTPFromDisplay); // mail.ReplyTo = md3; // } //} //mail.Subject = Subject; //mail.IsBodyHtml = true; //mail.Body = Body; //if (mail.AlternateViews.Count != 0) //{ // foreach (AlternateView altrView in mail.AlternateViews) // { // mail.AlternateViews.Add(altrView); // } //} //smtpClient.Send(mail); } foreach (object obj in Attachments) { Attachment attachment = attachment = new Attachment(obj.ToString()); email.Attachments.Add(attachment); } //SendMail(To, Cc, Bcc, email.Subject.ToString(), email.Body.ToString(), Attachments, from, dtAdviserSMTP,out fromSMTPEmail); email.Body = email.Body.Replace("[A_WEB_SITE]", advisorPreferenceVo.WebSiteDomainName.ToString()); email.Body = email.Body.Replace("[A_LOGO]", "<img src='cid:HDIImage' alt='Logo'>"); string logoPath = string.Empty; System.Net.Mail.AlternateView htmlView; System.Net.Mail.AlternateView plainTextView = System.Net.Mail.AlternateView.CreateAlternateViewFromString("Text view", null, "text/plain"); //System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(hidBody.Value.Trim() + "<image src=cid:HDIImage>", null, "text/html"); htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(email.Body, null, "text/html"); //Add image to HTML version if (advisorVo != null) { logoPath = _AdviserLogoDirectory + "\\" + advisorVo.LogoPath; } if (!File.Exists(logoPath)) { logoPath = _AdviserLogoDirectory + "\\spacer.png"; } //System.Net.Mail.LinkedResource imageResource = new System.Net.Mail.LinkedResource(Server.MapPath("~/Images/") + @"\3DSYRW_4009.JPG", "image/jpeg"); System.Net.Mail.LinkedResource imageResource = new System.Net.Mail.LinkedResource(logoPath, "image/jpeg"); imageResource.ContentId = "HDIImage"; htmlView.LinkedResources.Add(imageResource); //Add two views to message. email.AlternateViews.Add(plainTextView); email.AlternateViews.Add(htmlView); //SendMail(To, Cc, Bcc, email.Subject.ToString(), email.Body.ToString(), Attachments, from, dtAdviserSMTP, out fromSMTPEmail); SendMail(email, out statusMessage); }
private void SendMail(object o) { try { System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage(); if (to.Trim() == "") { return; } if (!to.Contains('@')) { return; } else if (to.Split('@')[1].Trim() == "") { return; } Thread.Sleep(1500); if (tip == "genel") { if (System.Configuration.ConfigurationSettings.AppSettings["MailAccount"] == null || System.Configuration.ConfigurationSettings.AppSettings["MailAccount"].ToString().Trim() == "" || System.Configuration.ConfigurationSettings.AppSettings["MailFromAddress"] == null || System.Configuration.ConfigurationSettings.AppSettings["MailFromAddress"].Trim() == "") { return; } msg.From = new MailAddress(System.Configuration.ConfigurationSettings.AppSettings["MailFromAddress"], System.Configuration.ConfigurationSettings.AppSettings["MailFromName"]); } msg.To.Add(to.Replace(";", ",")); if (reply_to != "") { msg.ReplyToList.Add(reply_to); } if (cc != "" && cc.Contains('@')) { msg.CC.Add(cc.Replace(";", ",")); } msg.Subject = subject; msg.Body = body; msg.IsBodyHtml = true; if (attacments != null) { foreach (System.Net.Mail.Attachment atc in attacments) { msg.Attachments.Add(atc); } } if (imgpath != "") { System.Net.Mail.LinkedResource imageResourceEs = new System.Net.Mail.LinkedResource(imgpath, "image/jpg"); imageResourceEs.TransferEncoding = System.Net.Mime.TransferEncoding.Base64; imageResourceEs.ContentId = "companylogo"; AlternateView av1 = AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html); av1.LinkedResources.Add(imageResourceEs); msg.AlternateViews.Add(av1); } try { if (System.Configuration.ConfigurationSettings.AppSettings["SMTPMailServer"] != "" && System.Configuration.ConfigurationSettings.AppSettings["SMTPMailServerPort"] != "") { System.Net.Mail.SmtpClient c = new SmtpClient(System.Configuration.ConfigurationSettings.AppSettings["SMTPMailServer"], int.Parse(System.Configuration.ConfigurationSettings.AppSettings["SMTPMailServerPort"])); if (tip == "genel") { c.Credentials = new System.Net.NetworkCredential(System.Configuration.ConfigurationSettings.AppSettings["MailAccount"], System.Configuration.ConfigurationSettings.AppSettings["MailAccountPwd"]); c.EnableSsl = true; } //c.ServicePoint.ConnectionLimit = 10; c.Send(msg); } } catch (Exception ex) { // BaseDB.DBManager.AppConnection.ExecuteSql("insert into log_mail values('" + to + "','" + msg.From.Address + "','" + gonderen_aktif_user_name + "','" + tip + "','" + subject + "','" + ex.Message + "',getdate())"); return; } } catch (Exception exp) { return; } }
protected void btnSendLoginWidGet_Click(object sender, EventArgs e) { Emailer emailer = new Emailer(); EmailMessage email = new EmailMessage(); AdviserStaffSMTPBo adviserStaffSMTPBo = new AdviserStaffSMTPBo(); AdviserStaffSMTPVo adviserStaffSMTPVo = new AdviserStaffSMTPVo(); string logoPath = string.Empty; bool isMailSent = false; email.GetAdviserLoginWidgetMail(Encryption.Encrypt(adviserVo.advisorId.ToString()), adviserVo.OrganizationName.Trim()); email.To.Add(txtLoginWidGetEmail.Text.Trim()); adviserStaffSMTPVo = adviserStaffSMTPBo.GetSMTPCredentials(1000); if (adviserStaffSMTPVo.HostServer != null && adviserStaffSMTPVo.HostServer != string.Empty) { emailer.isDefaultCredentials = !Convert.ToBoolean(adviserStaffSMTPVo.IsAuthenticationRequired); if (!String.IsNullOrEmpty(adviserStaffSMTPVo.Password)) { emailer.smtpPassword = Encryption.Decrypt(adviserStaffSMTPVo.Password); } emailer.smtpPort = int.Parse(adviserStaffSMTPVo.Port); emailer.smtpServer = adviserStaffSMTPVo.HostServer; emailer.smtpUserName = adviserStaffSMTPVo.Email; email.Body = email.Body.Replace("[ORGANIZATION]", "WealthERP Team"); if (ConfigurationSettings.AppSettings["HostName"].ToString() == "Wealtherp") { email.Body = email.Body.Replace("[WEBSITE]", "https://app.wealtherp.com/"); } email.Body = email.Body.Replace("[CONTACTPERSON]", "Mr Vijay Shenoy"); email.Body = email.Body.Replace("[DESIGNATION]", "Customer Care"); email.Body = email.Body.Replace("[PHONE]", "080 - 32429514"); email.Body = email.Body.Replace("[EMAIL]", "*****@*****.**"); email.Body = email.Body.Replace("[LOGO]", "<img src='cid:HDIImage' alt='Logo'>"); System.Net.Mail.AlternateView htmlView; System.Net.Mail.AlternateView plainTextView = System.Net.Mail.AlternateView.CreateAlternateViewFromString("Text view", null, "text/plain"); //System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(hidBody.Value.Trim() + "<image src=cid:HDIImage>", null, "text/html"); htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString("<html><body " + "style='font-family:Tahoma, Arial; font-size: 10pt;'><p>" + email.Body + "</p></body></html>", null, "text/html"); //Add image to HTML version logoPath = "~/Images/WealthERP.jpf"; if (!File.Exists(Server.MapPath(logoPath))) { logoPath = "~/Images/spacer.png"; } //System.Net.Mail.LinkedResource imageResource = new System.Net.Mail.LinkedResource(Server.MapPath("~/Images/") + @"\3DSYRW_4009.JPG", "image/jpeg"); System.Net.Mail.LinkedResource imageResource = new System.Net.Mail.LinkedResource(Server.MapPath(logoPath), "image/jpeg"); imageResource.ContentId = "HDIImage"; htmlView.LinkedResources.Add(imageResource); //Add two views to message. email.AlternateViews.Add(plainTextView); email.AlternateViews.Add(htmlView); //Send message //System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(); //Assign SMTP Credentials if configured. if (adviserStaffSMTPVo.HostServer != null && adviserStaffSMTPVo.HostServer != string.Empty) { emailer.isDefaultCredentials = !Convert.ToBoolean(adviserStaffSMTPVo.IsAuthenticationRequired); if (!String.IsNullOrEmpty(adviserStaffSMTPVo.Password)) { emailer.smtpPassword = Encryption.Decrypt(adviserStaffSMTPVo.Password); } emailer.smtpPort = int.Parse(adviserStaffSMTPVo.Port); emailer.smtpServer = adviserStaffSMTPVo.HostServer; emailer.smtpUserName = adviserStaffSMTPVo.Email; if (Convert.ToBoolean(adviserStaffSMTPVo.IsAuthenticationRequired)) { if (ConfigurationSettings.AppSettings["HostName"].ToString() == "Wealtherp") { email.From = new MailAddress(emailer.smtpUserName, "WealthERP Team"); } } } isMailSent = emailer.SendMail(email); if (isMailSent) { trSuccessMsg.Visible = true; //tblErrorMassage.Visible = false; divSuccessMsg.InnerText = "Login Widget send to this email Id"; } else { trSuccessMsg.Visible = false; //tblErrorMassage.Visible = true; divSuccessMsg.InnerText = "An error occurred while sending Login Widget"; } } }
private void StartSection(string section, ContentType sectionContentType, TransferEncoding transferEncoding, LinkedResource lr) { SendData(String.Format("--{0}", section)); SendHeader("content-type", sectionContentType.ToString()); SendHeader("content-transfer-encoding", GetTransferEncodingName(transferEncoding)); if (lr.ContentId != null && lr.ContentId.Length > 0) { SendHeader("content-ID", "<" + lr.ContentId + ">"); } SendData(string.Empty); }
protected void btnSendEmailToIFF_Click(object sender, EventArgs e) { int selectedRecords = 0; string statusMessage = string.Empty; advisorVo = (AdvisorVo)Session["advisorVo"]; AdvisorBo advisorBo = new AdvisorBo(); RMVo rmVo = new RMVo(); AdvisorStaffBo advisorStaffBo = new AdvisorStaffBo(); Random r = new Random(); string logoPath = string.Empty; if (Page.IsValid) { try { foreach (GridViewRow gvr in gvIFFUsers.Rows) { if (((CheckBox)gvr.FindControl("chkBoxChild")).Checked == true) { selectedRecords++; userId = int.Parse(gvIFFUsers.DataKeys[gvr.RowIndex].Value.ToString()); advisorVo = advisorBo.GetAdvisorUser(userId); rmVo = advisorStaffBo.GetAdvisorStaff(userId); Emailer emailer = new Emailer(); EmailMessage email = new EmailMessage(); string hassedPassword = string.Empty; string saltValue = string.Empty; string password = r.Next(20000, 100000).ToString(); userVo = userBo.GetUserDetails(userId); string userName = userVo.FirstName + " " + userVo.MiddleName + " " + userVo.LastName; encryption.GetHashAndSaltString(password, out hassedPassword, out saltValue); userVo.Password = hassedPassword; userVo.PasswordSaltValue = saltValue; userVo.OriginalPassword = password; userVo.IsTempPassword = 1; email.GetResetPasswordMail(userVo.LoginId, password, userName); //email.Subject = email.Subject.Replace("WealthERP", advisorVo.OrganizationName); //email.Subject = email.Subject.Replace("MoneyTouch", advisorVo.OrganizationName); //email.Body = email.Body.Replace("[ORGANIZATION]", advisorVo.OrganizationName); email.To.Add(userVo.Email); AdviserStaffSMTPBo adviserStaffSMTPBo = new AdviserStaffSMTPBo(); //int rmId = Convert.ToInt32(ViewState["rmId"]); AdviserStaffSMTPVo adviserStaffSMTPVo = adviserStaffSMTPBo.GetSMTPCredentials(1000); //adviserStaffSMTPVo.HostServer = ""; if (adviserStaffSMTPVo.HostServer != null && adviserStaffSMTPVo.HostServer != string.Empty) { emailer.isDefaultCredentials = !Convert.ToBoolean(adviserStaffSMTPVo.IsAuthenticationRequired); if (!String.IsNullOrEmpty(adviserStaffSMTPVo.Password)) { emailer.smtpPassword = Encryption.Decrypt(adviserStaffSMTPVo.Password); } emailer.smtpPort = int.Parse(adviserStaffSMTPVo.Port); emailer.smtpServer = adviserStaffSMTPVo.HostServer; emailer.smtpUserName = adviserStaffSMTPVo.Email; //email.Subject = email.Subject.Replace("WealthERP", advisorVo.OrganizationName); //email.Subject = email.Subject.Replace("MoneyTouch", advisorVo.OrganizationName); email.Body = email.Body.Replace("[ORGANIZATION]", "WealthERP Team"); if (ConfigurationSettings.AppSettings["HostName"].ToString() == "Wealtherp") { email.Body = email.Body.Replace("[WEBSITE]", "https://app.wealtherp.com/"); } email.Body = email.Body.Replace("[CONTACTPERSON]", "Customer Care"); email.Body = email.Body.Replace("[DESIGNATION]", "Team WealthERP"); email.Body = email.Body.Replace("[PHONE]", "+91 9663305249 <br/>Skype: custcare.ampsys"); email.Body = email.Body.Replace("[EMAIL]", "*****@*****.**"); email.Body = email.Body.Replace("[LOGO]", "<img src='cid:HDIImage' alt='Logo'>"); System.Net.Mail.AlternateView htmlView; System.Net.Mail.AlternateView plainTextView = System.Net.Mail.AlternateView.CreateAlternateViewFromString("Text view", null, "text/plain"); //System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(hidBody.Value.Trim() + "<image src=cid:HDIImage>", null, "text/html"); htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString("<html><body " + "style='font-family:Tahoma, Arial; font-size: 10pt;'><p>" + email.Body + "</p></body></html>", null, "text/html"); //Add image to HTML version logoPath = "~/Images/WealthERP.jpf"; if (!File.Exists(Server.MapPath(logoPath))) { logoPath = "~/Images/spacer.png"; } //System.Net.Mail.LinkedResource imageResource = new System.Net.Mail.LinkedResource(Server.MapPath("~/Images/") + @"\3DSYRW_4009.JPG", "image/jpeg"); System.Net.Mail.LinkedResource imageResource = new System.Net.Mail.LinkedResource(Server.MapPath(logoPath), "image/jpeg"); imageResource.ContentId = "HDIImage"; htmlView.LinkedResources.Add(imageResource); //Add two views to message. email.AlternateViews.Add(plainTextView); email.AlternateViews.Add(htmlView); //Send message //System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(); //Assign SMTP Credentials if configured. if (adviserStaffSMTPVo.HostServer != null && adviserStaffSMTPVo.HostServer != string.Empty) { emailer.isDefaultCredentials = !Convert.ToBoolean(adviserStaffSMTPVo.IsAuthenticationRequired); if (!String.IsNullOrEmpty(adviserStaffSMTPVo.Password)) { emailer.smtpPassword = Encryption.Decrypt(adviserStaffSMTPVo.Password); } emailer.smtpPort = int.Parse(adviserStaffSMTPVo.Port); emailer.smtpServer = adviserStaffSMTPVo.HostServer; emailer.smtpUserName = adviserStaffSMTPVo.Email; if (Convert.ToBoolean(adviserStaffSMTPVo.IsAuthenticationRequired)) { if (ConfigurationSettings.AppSettings["HostName"].ToString() == "Wealtherp") { email.From = new MailAddress(emailer.smtpUserName, "WealthERP Team"); } } } //if (Convert.ToBoolean(adviserStaffSMTPVo.IsAuthenticationRequired)) //{ // if (ConfigurationSettings.AppSettings["HostName"].ToString() == "Wealtherp") // { // email.From = new MailAddress(emailer.smtpUserName, advisorVo.OrganizationName); // } // else if (ConfigurationSettings.AppSettings["HostName"].ToString() == "MoneyTouch") // { // email.From = new MailAddress(emailer.smtpUserName, advisorVo.OrganizationName); // } //} } bool isMailSent = false; if (userBo.UpdateUser(userVo)) { isMailSent = emailer.SendMail(email); } if (isMailSent) { statusMessage = "Credentials have been reset & sent to selected Adviser"; tblMessage.Visible = true; tblErrorMassage.Visible = false; //ErrorMessage.Visible = false; SuccessMsg.InnerText = statusMessage; //SuccessMsg.Visible = true; } else { statusMessage = "An error occurred while sending mail to selected Adviser"; tblMessage.Visible = false; tblErrorMassage.Visible = true; //ErrorMessage.Visible = true; ErrorMessage.InnerText = statusMessage; //SuccessMsg.Visible = false; } } } tblErrorMassage.Visible = false; //ErrorMessage.Visible = false; } catch (BaseApplicationException Ex) { throw Ex; } catch (Exception Ex) { BaseApplicationException exBase = new BaseApplicationException(Ex.Message, Ex); NameValueCollection FunctionInfo = new NameValueCollection(); FunctionInfo.Add("Method", "RMCustomerUserDetails.ascx:btnGenerate_Click()"); exBase.AdditionalInformation = FunctionInfo; ExceptionManager.Publish(exBase); throw exBase; } } }