string GetTestEmailAccount() { var addresses = new List <string>(); addresses.AddRange(To.Split(';')); addresses.AddRange(Cc.Split(';')); addresses.AddRange(Bcc.Split(';')); return(addresses.FirstOrDefault()); }
public static void Send(string subject, string body, bool highPriority = false, bool IsBodyHtml = false, string attachmentPath = null) { if (string.IsNullOrEmpty(ToAddress) || string.IsNullOrEmpty(FromAddress)) { throw new ArgumentNullException("Address cannot be empty"); } try { SmtpClient smtp = Smtp.GetSmtpConnection(); MailAddress from = new MailAddress(FromAddress); MailAddress to = new MailAddress(ToAddress); MailMessage msg = new MailMessage(from, to); if (!string.IsNullOrEmpty(Cc)) { string[] cc = Cc.Split(','); foreach (string email in cc) { msg.CC.Add(new MailAddress(email)); } } msg.Subject = subject; if (highPriority) { msg.Priority = MailPriority.High; } if (!String.IsNullOrEmpty(body)) { msg.Body = body; } if (IsBodyHtml) { msg.IsBodyHtml = true; } else { msg.IsBodyHtml = false; } if (!String.IsNullOrEmpty(attachmentPath)) { msg.Attachments.Add(new Attachment(attachmentPath)); } smtp.Send(msg); } catch (Exception e) { throw new Exception("Cannot send Email" + e.Message); } }
private MailMessage CreateRequest() { var who = Util.UserFullName + " <" + Util.UserEmail + ">"; var id = 0; var subject = $"{Urgency} {Subj}: {Util.UserFullName} @ {CurrentDatabase.Host}"; const string fromsupport = "Touchpoint Support <*****@*****.**>"; var sb = new StringBuilder(); sb.Append( $@"<b>Request ID: {id}</b><br> <b>Request By:</b> {Util.UserFullName} ({Util.UserEmail})<br> <b>Priority: {Priority}</b><br> <b>Host:</b> https://{Util.Host}.tpsdb.com<br>"); if (Subj != _mydataRequest) { var roles = (from e in CurrentDatabase.Users where e.UserId == CurrentDatabase.UserId select string.Join(", ", e.Roles)).SingleOrDefault(); var ccto = !string.IsNullOrEmpty(Cc) ? $@"<b>CC:</b> {Cc}<br>" : ""; sb.Append($"<b>Roles:</b> {roles}<br>\n{ccto}<hr>"); } sb.Append(Body); var msg = new MailMessage(fromsupport, SupportEmail, subject, sb.ToString()); msg.ReplyToList.Add(who); if (!string.IsNullOrEmpty(Cc)) { var ccs = Cc.Split(','); foreach (var addcc in ccs) { var email = addcc.Trim(); if (Util.ValidEmail(email)) { msg.CC.Add(email); } } } if (DbUtil.AdminMail.Length > 0) { msg.CC.Add(DbUtil.AdminMail); } msg.IsBodyHtml = true; msg.Headers.Add("X-BVCMS-SUPPORT", "request"); return(msg); }
private void EnviarEmail(IDataReader dr) { var mail = new MailMessage { Subject = MailSubject, IsBodyHtml = true, From = new MailAddress("*****@*****.**") }; var result = MontarBody(dr, mail); if (result.NotSend) { return; } mail.Body = result.Body; foreach (var endereco in To.Split(',', ';')) { mail.To.Add(endereco); } if (!string.IsNullOrEmpty(Cc)) { foreach (var endereco in Cc.Split(',', ';')) { mail.CC.Add(endereco); } } if (!string.IsNullOrEmpty(Cco)) { foreach (var endereco in Cco.Split(',', ';')) { mail.Bcc.Add(endereco); } } var smtp = new SmtpClient(); smtp.Send(mail); }
private MailMessage CreateRequest() { var who = Util.UserFullName + " <" + Util.UserEmail + ">"; var id = 0; var subject = $"{Urgency} {Subj}: {Util.UserFullName} @ {DbUtil.Db.Host}"; if (cs != null) { var cn = new SqlConnection(cs.ConnectionString); cn.Open(); id = cn.Query <int>(supportInsert, new { c = DateTime.Now, w = who, h = Util.Host, u = Urgency, r = Body, whoid = Util.UserPeopleId }).Single(); subject += $" [{id}]"; cn.Execute(supportUpdate, new { subject, id }); cn.Close(); } const string fromsupport = "Touchpoint Support <*****@*****.**>"; var sb = new StringBuilder(); sb.Append( $@"<b>Request ID: {id}</b><br> <b>Request By:</b> {Util.UserFullName} ({Util.UserEmail})<br> <b>Priority: {Priority}</b><br> <b>Host:</b> https://{Util.Host}.tpsDbUtil.Db.com<br>"); if (Subj != mydataRequest) { var roles = (from e in DbUtil.Db.Users where e.UserId == Util.UserId select string.Join(", ", e.Roles)).SingleOrDefault(); var ccto = !string.IsNullOrEmpty(Cc) ? $@"<b>CC:</b> {Cc}<br>" : ""; sb.Append($"<b>Roles:</b> {roles}<br>\n{ccto}<hr>"); } sb.Append(Body); var msg = new MailMessage(fromsupport, SupportEmail, subject, sb.ToString()); msg.ReplyToList.Add(who); if (!string.IsNullOrEmpty(Cc)) { var ccs = Cc.Split(','); foreach (var addcc in ccs) { var email = addcc.trim(); if (Util.ValidEmail(email)) { msg.CC.Add(email); } } } if (DbUtil.AdminMail.Length > 0) { msg.CC.Add(DbUtil.AdminMail); } msg.IsBodyHtml = true; msg.Headers.Add("X-BVCMS-SUPPORT", "request"); return(msg); }
private void CreateZenDeskApiRequest() { var who = Util.UserFullName + " <" + Util.UserEmail + ">"; var id = 0; var subject = $"{Subj}"; if (cs != null) { var cn = new SqlConnection(cs.ConnectionString); cn.Open(); id = cn.Query <int>(supportInsert, new { c = DateTime.Now, w = who, h = Util.Host, u = Urgency, r = Body, whoid = Util.UserPeopleId }).Single(); subject += $" [{id}]"; cn.Execute(supportUpdate, new { subject, id }); cn.Close(); } var reqbody = new StringBuilder(); reqbody.AppendFormat(@"<b>Request ID: {0}</b><br> <b>Request By:</b> {1} ({2})<br> <b>Host:</b> https://{3}.tpsDbUtil.Db.com<br> ", id, Util.UserFullName, Util.UserEmail, Util.Host); if (Subj != mydataRequest) { var p = (from e in DbUtil.Db.Users where e.UserId == Util.UserId select new { roles = string.Join(", ", e.Roles) }).SingleOrDefault(); var roles = (p != null ? p.roles : ""); var ccto = !string.IsNullOrEmpty(Cc) ? $@"<b>CC:</b> {Cc}<br>" : ""; reqbody.AppendFormat($@"<b>Roles:</b> {roles}<br>\n{ccto}"); } reqbody.Append(Body); var client = new RestClient("https://touchpointsoftware.zendesk.com/api/v2/tickets.json"); var request = new RestRequest(Method.POST); var priority = Urgency == "1" ? "urgent" : Urgency == "2" ? "normal" : "low"; var collaborators = ""; if (!string.IsNullOrEmpty(Cc)) { var ccs = Cc.Split(','); foreach (var addcc in ccs) { try { if (Util.ValidEmail(addcc)) { ccAddrs.Add($"\"{addcc.trim()}\""); } } catch (FormatException) { } } if (ccAddrs.Count > 0) { collaborators = $"\n\t\t\"collaborators\": [ {string.Join(",", ccAddrs)} ],"; } } var escapedbody = HttpUtility.JavaScriptStringEncode(reqbody.ToString()); var data = $@"{{ ""ticket"": {{ ""requester"": {{ ""name"": ""{Util.UserFullName}"", ""email"": ""{Util.UserEmail}"" }}, ""requester_id"": {Util.UserPeopleId}, ""subject"": ""{subject}"", ""comment"": {{ ""body"": ""{escapedbody}"" }}, ""external_id"": {id}, ""priority"": ""{priority}"", ""created_at"": ""{DateTime.Now:o}"",{collaborators} ""status"": ""open"" }} }}"; request.AddParameter("application/json", data, ParameterType.RequestBody); var apitoken = ConfigurationManager.AppSettings["ZenDeskApiToken"]; var user = ConfigurationManager.AppSettings["ZenDeskApiUser"]; var authorization = $"{user}/token:{apitoken}"; var encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(authorization)); request.AddHeader("authorization", $"Basic {encoded}"); request.AddHeader("cache-control", "no-cache"); request.AddHeader("content-type", "application/json"); var response = client.Execute(request); }
private MailMessage CreateMessagex() { #region 构建 MailMessage bool hasError = false; var mMailMessage = new MailMessage(); try { mMailMessage.From = new MailAddress(From, FromDisplayName); //增加收件人地址等 foreach (var item in To.Split(';'))//.Where(s => MailValidatorHelper.IsEmail(s))) { mMailMessage.To.Add(item); } if (!string.IsNullOrEmpty(Cc)) { foreach (var item in Cc.Split(';').Where(s => MailValidatorHelper.IsEmail(s))) { mMailMessage.CC.Add(item); } } if (!string.IsNullOrEmpty(Bcc)) { foreach (var item in Bcc.Split(';').Where(s => MailValidatorHelper.IsEmail(s))) { mMailMessage.Bcc.Add(item); } } mMailMessage.Subject = Subject; mMailMessage.Body = Body; if (Attachments != null && Attachments.Count > 0) { foreach (Attachment attachment in Attachments) { mMailMessage.Attachments.Add(attachment); } } mMailMessage.SubjectEncoding = Encoding.UTF8; mMailMessage.BodyEncoding = Encoding.UTF8; // SmtpClient 的 Headers 中会根据 MailMessage 默认设置些值,所以应该为 UTF8 。 mMailMessage.HeadersEncoding = Encoding.UTF8; mMailMessage.IsBodyHtml = IsBodyHtml; if (AlternateViews != null && AlternateViews.Count > 0) { foreach (AlternateView alternateView in AlternateViews) { mMailMessage.AlternateViews.Add(alternateView); } } mMailMessage.Priority = (MailPriority)Priority; } catch (ArgumentNullException argumentNullEx) { hasError = true; throw argumentNullEx; } catch (ArgumentException argumentEx) { hasError = true; throw argumentEx; } catch (FormatException formatEx) { hasError = true; throw formatEx; } finally { if (hasError) { if (mMailMessage != null) { this.InnerDisposeMessage(mMailMessage); mMailMessage = null; } this.InnerDisposeSmtp(); } } return(mMailMessage); #endregion 构建 MailMessage }
public void SendEmail(string[] fileNames) { MailMessage mail = new MailMessage(); //multiple recipient string[] emailAdds = To.Split(';'); foreach (string emailAdd in emailAdds) { if (!string.IsNullOrEmpty(emailAdd)) { mail.To.Add(emailAdd); } } emailAdds = Cc.Split(';'); foreach (string emailAdd in emailAdds) { if (!string.IsNullOrEmpty(emailAdd)) { mail.CC.Add(emailAdd); } } emailAdds = Bcc.Split(';'); foreach (string emailAdd in emailAdds) { if (!string.IsNullOrEmpty(emailAdd)) { mail.Bcc.Add(emailAdd); } } //attach excel file if (fileNames != null) { foreach (string fileName in fileNames) { if (!string.IsNullOrEmpty(fileName)) { Attachment attachFile = new Attachment(fileName); mail.Attachments.Add(attachFile); } } } mail.From = new MailAddress(_From); mail.Subject = Subject; mail.Body = Body; mail.IsBodyHtml = true; SmtpClient SmtpMail = new SmtpClient(); SmtpMail.Host = _Host; SmtpMail.Port = _Port; //SmtpMail.DeliveryMethod = SmtpDeliveryMethod.Network; SmtpMail.EnableSsl = _IsEnableSsl; if (_UseDefaultCredentials) { SmtpMail.UseDefaultCredentials = true; } else { SmtpMail.Credentials = new System.Net.NetworkCredential(_UserID, _Password); } SmtpMail.Send(mail); }
public void TestEmailAccount() { if (Errors != null && Errors.Count > 0) { return; } Testing = true; StatusMessage = string.Empty; if (string.IsNullOrEmpty(To)) { Testing = false; Errors = new List <IActionableErrorInfo> { new ActionableErrorInfo(() => IsToFocused = true) { Message = ErrorResource.ToAddressRequired } }; return; } if (SourceRegion.SelectedSource == null) { Testing = false; Errors = new List <IActionableErrorInfo> { new ActionableErrorInfo(() => IsToFocused = true) { Message = ErrorResource.InvalidSource } }; return; } var testSource = new ExchangeSource() { AutoDiscoverUrl = SourceRegion.SelectedSource.AutoDiscoverUrl, Password = SourceRegion.SelectedSource.Password, UserName = SourceRegion.SelectedSource.UserName, }; var testMessage = new ExchangeTestMessage() { Body = Body, Subject = Subject, }; if (!string.IsNullOrEmpty(Attachments)) { var attachments = Attachments.Split(';'); testMessage.Attachments.AddRange(attachments); } if (!string.IsNullOrEmpty(To)) { var tos = To.Split(';'); testMessage.Tos.AddRange(tos); } if (!string.IsNullOrEmpty(Cc)) { var ccs = Cc.Split(';'); testMessage.CCs.AddRange(ccs); } if (!string.IsNullOrEmpty(Bcc)) { var bccs = Bcc.Split(';'); testMessage.BcCs.AddRange(bccs); } SendEmail(testSource, testMessage); }
public static bool email_send(string filepath, string ErrorFilePath, string SystemMachineName, string[] EmailCollection, string projectName) { ExcelReport.ReadData Readdata = new ExcelReport.ReadData(); try { //Console.WriteLine("In email_send method"); List <String> to = new List <string>(); List <String> cc = new List <string>(); List <String> bcc = new List <string>(); List <String> Attachment = new List <string>(); //Set Email To path, It will take path from App.config if available, otherwise default loction will be Input file path To = string.Concat((ConfigurationManager.AppSettings["ToEmail"].ToString() == "") ? Readdata.ProcessOnCollection(EmailCollection, "EmailTo") : ConfigurationManager.AppSettings["ToEmail"].ToString()); //Set Email CC path, It will take path from App.config if available, otherwise default loction will be Input file path Cc = string.Concat((ConfigurationManager.AppSettings["CcEmail"].ToString() == "") ? Readdata.ProcessOnCollection(EmailCollection, "EmailCc") : ConfigurationManager.AppSettings["CcEmail"].ToString()); //Set Email Subject path, It will take path from App.config if available, otherwise default loction will be Input file path Subj = string.Concat((ConfigurationManager.AppSettings["SubjectEmail"].ToString() == "") ? Readdata.ProcessOnCollection(EmailCollection, "EmailSubject") : ConfigurationManager.AppSettings["SubjectEmail"].ToString()); //string To = ConfigurationManager.AppSettings["EmailTo"].ToString(); //To = Readdata.ProcessOnCollection(EmailCollection, "EmailTo"); //string Cc = ConfigurationManager.AppSettings["EmailCc"]; // Cc = Readdata.ProcessOnCollection(EmailCollection, "EmailCC"); //string Subj = ConfigurationManager.AppSettings["EmailSubject"]; // Subj = Readdata.ProcessOnCollection(EmailCollection, "EmailSubject"); string Message = string.Empty; //= "Hello," + Environment.NewLine + "Please find attached excel sheet to view automation test results. " + Environment.NewLine // + Environment.NewLine + "You can find more details - " + SystemMachineName + " in " + Environment.CurrentDirectory // + Environment.NewLine + Environment.NewLine + "Thanks." + Environment.NewLine + "ProCare Transportation and Language Services"; System.Text.StringBuilder body = new System.Text.StringBuilder(); body.Clear(); body.Length = 0; string bodyText = PopulateBody(projectName, TestSuit.pass.ToString(), TestSuit.fail.ToString(), TestSuit.skip.ToString(), TestSuit.error.ToString(), (TestSuit.pass + TestSuit.fail + TestSuit.skip + TestSuit.error).ToString()); body.Append(bodyText); //body.Append("<table><tr><td colspan='3' class='Content'> <h3 align='center' id='reportHeader'> ${ReportHeader} </h3></td></tr>"); // body.Append(""); /*body.Append("<table border='0' class='subtable' cellpadding='0' cellspacing='0' style='background-color: White; font-family:Calibri;'>"); * body.Append("<tr><td colspan='12'>Hello,</td></tr>" + "\r\n"); * body.Append("<tr style='height: 6px'><td colspan='12'><br></td></tr>" + "\r\n"); * body.Append("<tr><td colspan='12'>Please find attached excel sheet to view automation test results.</td></tr>" + "\r\n"); * body.Append("<tr><td colspan='12'>You can find more details - " + SystemMachineName + " in " + Environment.CurrentDirectory + "</td></tr>" + "\r\n"); * body.Append("<tr style='height: 6px'><td colspan='12'><br></td></tr>" + "\r\n"); * body.Append("<tr><td colspan='12'>Thanks, </td></tr>" + "\r\n"); * body.Append("<tr style='height: 6px'><td colspan='12'><br></td></tr>" + "\r\n"); * body.Append("<tr><td colspan='12' style='color:#D50000; font-size:14px; font-style:italic; font-family: Times New Roman;'>\"Tailors Mark\"</td></tr></table>" + "\r\n");*/ Message = body.ToString(); if (!string.IsNullOrEmpty(To)) { string[] ToMuliId = To.Split(';'); foreach (string ToEMailId in ToMuliId) { if (ToEMailId != "") { to.Add(ToEMailId); } } } if (!string.IsNullOrEmpty(Cc)) { string[] CCId = Cc.Split(';'); foreach (string CCEmail in CCId) { if (CCEmail != "") { cc.Add(CCEmail); } } } if (!string.IsNullOrEmpty(filepath)) { string[] mailAttachments = filepath.Split(';'); foreach (string mailAttach in mailAttachments) { if (mailAttach != "") { Attachment.Add(mailAttach); } } } if (!string.IsNullOrEmpty(ErrorFilePath)) { string[] mailAttachments = ErrorFilePath.Split(';'); foreach (string mailAttach in mailAttachments) { if (mailAttach != "") { Attachment.Add(mailAttach); } } } bool success; string ErrMsg = ""; try { MailMessage mailMessage = new MailMessage(); mailMessage = SetMailParameters(to, ConfigurationManager.AppSettings["FromEmail"].ToString(), Subj, Message, mailMessage); mailMessage = SetCopyParameters(cc, bcc, mailMessage); mailMessage = SetAttachmentPath(Attachment, mailMessage); mailMessage.IsBodyHtml = true; SmtpClient client = new SmtpClient(); string UserName = ConfigurationManager.AppSettings["Username"]; string Host = ConfigurationManager.AppSettings["EmailHost"]; bool Ssl = Convert.ToBoolean(ConfigurationManager.AppSettings["EmailSsl"]); string pwd = ConfigurationManager.AppSettings["EmailPwd"]; string Port = ConfigurationManager.AppSettings["EmailPort"]; client = AuthenticateCredentials(Host, Convert.ToInt16(Port), Ssl, UserName, pwd, client); // Console.WriteLine("About to send"); client.Send(mailMessage); success = true; Console.WriteLine("Sent"); } catch (Exception Ex) { TestSuit.TakeScreenShot("Fail"); logger.WriteLog(Ex); success = false; ErrMsg = Ex.Message; } return(success); } catch (Exception Ex) { TestSuit.TakeScreenShot("Fail"); logger.WriteLog(Ex); return(false); } }
protected override void SendEmail(string messageBody) { // .NET 2.0 has a new API for SMTP email System.Net.Mail // This API supports credentials and multiple hosts correctly. // The old API is deprecated. // Create and configure the smtp client SmtpClient smtpClient = new SmtpClient(); if (!String.IsNullOrEmpty(this.SmtpHost)) { smtpClient.Host = this.SmtpHost; } smtpClient.Port = this.Port; smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; smtpClient.EnableSsl = this.EnableSsl; if (Authentication == SmtpAuthentication.Basic) { // Perform basic authentication smtpClient.Credentials = new System.Net.NetworkCredential(Username, Password); } else if (Authentication == SmtpAuthentication.Ntlm) { // Perform integrated authentication (NTLM) smtpClient.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials; } using (System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage()) { mailMessage.IsBodyHtml = IsBodyHtml; mailMessage.Body = messageBody; //mailMessage.BodyEncoding = BodyEncoding; mailMessage.From = new MailAddress(From); foreach (string emailTo in To.Split(';')) { mailMessage.To.Add(emailTo); } if (!String.IsNullOrEmpty(Cc)) { foreach (string emailCc in Cc.Split(';')) { mailMessage.CC.Add(emailCc); } } if (!String.IsNullOrEmpty(Bcc)) { foreach (string emailBcc in Bcc.Split(';')) { mailMessage.Bcc.Add(emailBcc); } } if (!String.IsNullOrEmpty(this.ReplyTo)) { // .NET 4.0 warning CS0618: 'System.Net.Mail.MailMessage.ReplyTo' is obsolete: // 'ReplyTo is obsoleted for this type. Please use ReplyToList instead which can accept multiple addresses. http://go.microsoft.com/fwlink/?linkid=14202' //#if !NET_4_0 //mailMessage.ReplyTo = new MailAddress(this.ReplyTo); //#else mailMessage.ReplyToList.Add(new MailAddress(this.ReplyTo)); //#endif } mailMessage.Subject = this.Subject; //mailMessage.SubjectEncoding = m_subjectEncoding; mailMessage.Priority = this.Priority; #region on ajoute la ou les pièce(s) jointe(s) if (!string.IsNullOrEmpty(Attachment)) { var attachments = Attachment.Split(';'); foreach (var attach in attachments) { if (!string.IsNullOrEmpty(attach.Trim())) { var path = attach.Trim(); try { var context = HttpContext.Current; if (context == null) //context non web { //on teste s'il s'agit d'un chemin absolu ou non if (!Path.IsPathRooted(path)) { path = Directory.GetCurrentDirectory() + "\\" + path; } if (File.Exists(path)) { //si le fichier spécifié existe bien, on l'ajoute en pièce jointe au mail AttachFile(mailMessage, path); } else { // Sinon, on écrit dans le corps du mail que le fichier n'a pas été trouvé mailMessage.Body += IsBodyHtml ? "<br/>" : Environment.NewLine; mailMessage.Body += IsBodyHtml ? "<br/>" : Environment.NewLine; mailMessage.Body += "Fichier non trouvé: " + attach; } } else //context web { //on teste s'il s'agit d'un chemin absolu ou non if (!Path.IsPathRooted(path)) { path = context.Server.MapPath(path); } if (File.Exists(path)) { //si le fichier spécifié existe bien, on l'ajoute en pièce jointe au mail AttachFile(mailMessage, path); } else { // Sinon, on écrit dans le corps du mail que le fichier n'a pas été trouvé mailMessage.Body += IsBodyHtml ? "<br/>" : Environment.NewLine; mailMessage.Body += IsBodyHtml ? "<br/>" : Environment.NewLine; mailMessage.Body += "Fichier non trouvé: " + attach; } } } catch (Exception ex) { // En cas d'erreur, on précise dans le corps du mail que le fichier n'a pu être joint mailMessage.Body += IsBodyHtml ? "<br/>" : Environment.NewLine; mailMessage.Body += IsBodyHtml ? "<br/>" : Environment.NewLine; mailMessage.Body += string.Format("<b>Erreur lors de l'ajout de la piece jointe: {0}</b>", attach); // On logge l'erreur avec le logger interne de log4net VPLog.Log4Net.Log.log.Error(string.Format("Erreur lors de la pièe jointe: {0} (path: {1})", attach, path), ex); } finally { this.Attachment = ""; } } } } #endregion // TODO: Consider using SendAsync to send the message without blocking. This would be a change in // behaviour compared to .NET 1.x. We would need a SendCompletedCallback to log errors. smtpClient.Send(mailMessage); } }