public static IRestResponse SendMailgunMessage(EmailItem item) { RestClient client = new RestClient(); client.BaseUrl = new Uri("https://api.mailgun.net/v3", UriKind.Absolute); client.Authenticator = new HttpBasicAuthenticator("api", "key-24a7017e23319bc7f734bbb356380287"); RestRequest request = new RestRequest(); request.AddParameter("domain", "sandboxbe96dda245f84804bdc04cd1caaf7483.mailgun.org", ParameterType.UrlSegment); request.Resource = "{domain}/messages"; request.AddParameter("from", "Mailgun Sandbox <*****@*****.**>"); request.AddParameter("to", item.EmailTO); if (!String.IsNullOrEmpty(item.EmailCC)) { request.AddParameter("cc", item.EmailCC); } if (!String.IsNullOrEmpty(item.EmailBCC)) { request.AddParameter("bcc", item.EmailBCC); } request.AddParameter("subject", String.IsNullOrEmpty(item.Subject) ? "Hello" : item.Subject); request.AddParameter("text", String.IsNullOrEmpty(item.Contents) ? "Congratulations! You have just sent an email!" : item.Contents); request.Method = Method.POST; return(client.Execute(request)); }
public EmailItem createFakeEmailItem(int subjectNumber, int messageNumber, int year, int month, int day, int hour, int minute, int second) { try { string name = createName(); string emailAddress = createEmail(name); string subject = createSubject(subjectNumber); string message = createMessage(messageNumber); DateTime timeStamp = createTimeStampSent(year, month, day, hour, minute, second); EmailItem fakeEmailItem = new EmailItem(); fakeEmailItem.fromName = name; fakeEmailItem.toEmailAddress = emailAddress; fakeEmailItem.toSubject = subject; fakeEmailItem.toMessage = message; fakeEmailItem.emailSentTimeStamp = timeStamp; return(fakeEmailItem); } catch (Exception ex) { //TODO: Handle this at some time in the future! return(null); } }
public ServiceResult SendEmail(EmailItem email) { var smtpMail = new SmtpMail(ClientCode) { From = Email, To = Email, TextBody = $"Contact detail: {email.SenderContactDetails}, Senders name: {email.SenderName} Message: {email.Message}" }; var smtpServer = new SmtpServer(GoogleSmtp, 465) { User = Email, Password = Password, Port = 465, ConnectType = SmtpConnectType.ConnectSSLAuto }; try { var smtpClient = new SmtpClient(); smtpClient.SendMail(smtpServer, smtpMail); return(new ServiceResult()); } catch (Exception ep) { return(new ServiceResult(ep.Message)); } }
public IEnumerable <EmailItem> GetAllEmailItems() { EmailSenderSeeder seeder = new EmailSenderSeeder(); List <EmailItem> sendList = new List <EmailItem>(); //First Email Item EmailItem firstEmailItem = seeder.createFakeEmailItem(1, 1, 1973, 6, 9, 13, 07, 44); sendList.Add(firstEmailItem); //Setup for creating the random emails. double incremenetor = 1.0; int counter = 1; Random randomNumber = new Random(); for (int j = 1; j <= 12; j++) { for (int i = 0; i < Math.Round(100 * incremenetor); i++) { sendList.Add(seeder.createFakeEmailItem(counter, //Subject Number counter, //Message Number 2017, //Year j, //Month randomNumber.Next(1, 28), //Day randomNumber.Next(6, 23), //Hour randomNumber.Next(1, 60), //Minute randomNumber.Next(1, 60))); //Second counter++; } incremenetor += 0.1; } return(sendList); }
public static IMail MakeMail(EmailItem email, TemplateItem template, string from) { var body = template.Make(email.Value); IFluentMail mail; if (template.IsHtml) { mail = Mail.Html(""); var matches = Regex.Matches(body, @"<img[^<>]+src=""?([^""\s<>]+)", RegexOptions.IgnoreCase); for (int i = 0, length = matches.Count; i < length; i++) { var file = matches[i].Groups[1].Value; if (file.IndexOf("//") >= 0 || !File.Exists(file)) { continue; } body = body.Replace(file, "cid:img" + i); mail.AddVisual(file).SetContentId("img" + i); } mail.Html(body); } else { mail = Mail.Text(body); } foreach (var file in template.Attachment) { mail.AddAttachment(file).SetFileName(Path.GetFileName(file)); } return(mail.To(email.Email) .From(from) .Subject(template.Title) .Create()); }
public async Task <bool> SendEmail(string toEmail, string emailTemplate, Dictionary <string, string> bodyReplacementValues, Dictionary <string, string> subjectReplacementValues) { var hermesApi = ConfigurationManager.AppSettings["HermesApi"]; var applicationId = Convert.ToInt16(ConfigurationManager.AppSettings["ApplicationId"]); var authorizationToken = ConfigurationManager.AppSettings["EmailAuthorizationToken"]; var sendEmails = Convert.ToBoolean(ConfigurationManager.AppSettings["SendEmails"] ?? "false"); var sendEmailClient = new SendEmailClient(hermesApi); if (sendEmails) { if (!String.IsNullOrEmpty(toEmail)) { var emailItem = new EmailItem { ToEmail = toEmail, ApplicationId = applicationId, EmailTemplate = emailTemplate, AuthorizationToken = authorizationToken, ReplacementValues = bodyReplacementValues, SubjectReplacementValues = subjectReplacementValues }; await sendEmailClient.SendEmailAsync(emailItem); return(true); } return(false); } return(false); }
private async void Logout_Click(object sender, RoutedEventArgs e) { ContentDialog dialog = new ContentDialog { Title = "警告", PrimaryButtonText = "继续", CloseButtonText = "取消", Content = "此操作将注销当前账户\r\r可能需要重新输入相关信息,是否继续?", Background = Application.Current.Resources["DialogAcrylicBrush"] as Brush }; if ((await dialog.ShowAsync()) != ContentDialogResult.Primary) { return; } LoadingText.Text = "正在注销..."; LoadingControl.IsLoading = true; ConnectionCancellation?.Cancel(); await Task.Delay(1000); ConnectionCancellation?.Dispose(); ConnectionCancellation = null; DisplayMode.SelectionChanged -= DisplayMode_SelectionChanged; LastSelectedItem = null; if (EmailProtocolServiceProvider.CheckWhetherInstanceExist()) { EmailProtocolServiceProvider.GetInstance().Dispose(); } EmailService = null; ApplicationData.Current.LocalSettings.Values["EmailStartup"] = null; ApplicationData.Current.RoamingSettings.Values["EmailCredentialName"] = null; ApplicationData.Current.RoamingSettings.Values["EmailCredentialPassword"] = null; ApplicationData.Current.RoamingSettings.Values["EmailIMAPAddress"] = null; ApplicationData.Current.RoamingSettings.Values["EmailIMAPPort"] = null; ApplicationData.Current.RoamingSettings.Values["EmailSMTPAddress"] = null; ApplicationData.Current.RoamingSettings.Values["EmailSMTPPort"] = null; ApplicationData.Current.RoamingSettings.Values["EmailEnableSSL"] = null; ApplicationData.Current.RoamingSettings.Values["EmailCallName"] = null; LoadingControl.IsLoading = false; await Task.Delay(700); EmailAllItemCollection.Clear(); EmailNotSeenItemCollection.Clear(); EmailDisplayCollection?.Clear(); EmailPage.ThisPage.Nav.Navigate(typeof(EmailStartupOne), EmailPage.ThisPage.Nav, new DrillInNavigationTransitionInfo()); NothingDisplayControl.Visibility = Visibility.Visible; }
public async Task <BaseResult> CreateOrUpdate(EmailItem newEmail) { var email = newEmail.ToEmail(); var rs = new BaseResult() { Result = Result.Success }; return(email.Id <= 0 ? await Create(email) : await Update(email)); }
public void LcdWrite(EmailItem Item) { String InfoString1 = "From: " + Item.From; String InfoString2 = "Subject: " + Item.Subject; G510Display.Source.Fonts.Font DrawFont = Image.Font_4x6_tf; DrawFont.DrawString(0, LogitechInterface.LOGI_LCD_MONO_HEIGHT - (2 * DrawFont.GetYSpacing()), InfoString1); DrawFont.DrawString(0, LogitechInterface.LOGI_LCD_MONO_HEIGHT - (1 * DrawFont.GetYSpacing()), InfoString2); }
public ActionResult ContactUs(EmailItem emailItem) { if (!ModelState.IsValid) { return(View(emailItem)); } ServiceResult serviceResult = _mailService.SendEmail(emailItem); string message = !serviceResult.Succeeded ? serviceResult.Errors.FirstOrDefault() : "Successfuly sent!"; return(RedirectToAction("SentResult", new { result = message })); }
public List <EmailItem> GetAirExportShippingNoticeEmailItems(int ELT_ACCOUNT_NUMBER, string BillNum, BillType billType) { List <EmailItem> eitems = new List <EmailItem>(); var hbItems = AirExportDA.GetAirExportDocumentList(ELT_ACCOUNT_NUMBER, BillNum, billType.ToString().Split('_')[1]); if (hbItems.Count() > 0) { var shippers = (from c in hbItems where string.IsNullOrEmpty(c.shipper_account_number) != true select c.shipper_account_number).Distinct(); int itemid = 1; foreach (var shipper in shippers) { var hawbs = (from c in hbItems where c.shipper_account_number == shipper select c).ToList(); EmailItem eitem = new EmailItem() { RecipientRelation = "Shipper", Attachments = new List <EmailAttachment>(), RecipientEmail = hawbs[0].shipper_email, RecipientName = hawbs[0].shipper_name, EmailType = EmailType.AirExport_Agent_PreAlert, IsSelected = true, EmailItemID = itemid++ }; if (hbItems[0].isDirect != "Y") { foreach (var h in hawbs) { eitem.Attachments.Add(new EmailAttachment() { IsSelected = true, GeneratorPath = string.Format("~/ASP/air_export/hawb_pdf.asp?HAWB={0}&Copy=CONSIGNEE", h.hawb_num), FileName = string.Format("HAWB {0}.pdf", h.hawb_num) }); if (!string.IsNullOrEmpty(h.invoice_no) && h.invoice_no != "-1") { eitem.Attachments.Add(new EmailAttachment() { IsSelected = true, GeneratorPath = string.Format("~/ASP/acct_tasks/invoice_pdf.asp?InvoiceNo={0}", h.invoice_no), FileName = string.Format("INV {0}.pdf", h.invoice_no) }); } } } else //Direct Master { eitem.Attachments.Add(new EmailAttachment() { IsSelected = true, GeneratorPath = string.Format("~/ASP/air_export/mawb_pdf.asp?MAWB={0}&Copy=Shipper", hbItems[0].mawb_num), FileName = string.Format("MAWB {0}.pdf", hbItems[0].mawb_num) }); if (!string.IsNullOrEmpty(hbItems[0].invoice_no) && hbItems[0].invoice_no != "-1") { eitem.Attachments.Add(new EmailAttachment() { IsSelected = true, GeneratorPath = string.Format("~/ASP/acct_tasks/invoice_pdf.asp?InvoiceNo={0}", hbItems[0].invoice_no), FileName = string.Format("INV {0}.pdf", hbItems[0].invoice_no) }); } } eitems.Add(eitem); } } return(eitems); }
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "json"; Pop3Client client = new Pop3Client(); client.Host = "pop.126.com"; client.Username = "******"; client.Password = "******"; client.Port = 110; client.SecurityMode = Pop3SslSecurityMode.Implicit; string result = string.Empty; try { int messageCount = client.GetMessageCount(); MailMessage msg; string mailSender = string.Empty; List <EmailItem> items = new List <EmailItem>(); EmailItem emailItem = new EmailItem(); for (int i = messageCount; i >= messageCount - 2; i--) { msg = client.FetchMessage(i); if (!string.IsNullOrEmpty(msg.From.DisplayName)) { mailSender = msg.From.DisplayName; } else { mailSender = msg.From.Address.Substring(0, msg.From.Address.LastIndexOf('@')); } items.Add(new EmailItem { Subject = msg.Subject, SendDate = msg.Date, Sender = mailSender }); emailItem.Items = items; } result = JsonConvert.SerializeObject(emailItem, Formatting.Indented); } catch (Exception ex) { result = string.Empty; } finally { client.Disconnect(); } context.Response.Write(result); }
public List <EmailItem> GetOceanExportAgentPreAlertEmailItems(int ELT_ACCOUNT_NUMBER, string BillNum, BillType billType) { List <EmailItem> eitems = new List <EmailItem>(); var hbItems = OceanExportDA.GetOceanExportDocumentList(ELT_ACCOUNT_NUMBER, BillNum, billType.ToString().Split('_')[1]); if (hbItems.Count() > 0) { var agents = (from c in hbItems where string.IsNullOrEmpty(c.agent_no) != true select c.agent_no).Distinct(); int itemid = 1; foreach (var agent in agents) { var hbols = (from c in hbItems where c.agent_no == agent select c).ToList(); EmailItem eitem = new EmailItem() { RecipientRelation = "Agent", Attachments = new List <EmailAttachment>(), RecipientEmail = hbols[0].agent_email, RecipientName = hbols[0].agent_name, EmailType = EmailType.OceanExport_Agent_PreAlert, IsSelected = true, EmailItemID = itemid++ }; eitem.Attachments.Add(new EmailAttachment() { IsSelected = true, GeneratorPath = string.Format("~/ASP/Ocean_export/manifest_pdf.asp?MBOL={0}&Agent={1}&MasterAgentNo={2}", hbItems[0].mbol_num, agent, hbItems[0].master_agent), FileName = string.Format("Manifest {0}.pdf", hbItems[0].mbol_num) }); if (hbItems[0].isDirect != "Y") { foreach (var h in hbols) { eitem.Attachments.Add(new EmailAttachment() { IsSelected = true, GeneratorPath = string.Format("~/ASP/Ocean_export/hbol_pdf.asp?hbol={0}&Copy=CONSIGNEE", h.hbol_num), FileName = string.Format("HBOL {0}.pdf", h.hbol_num) }); if (!string.IsNullOrEmpty(h.invoice_no) && h.invoice_no != "-1") { eitem.Attachments.Add(new EmailAttachment() { IsSelected = true, GeneratorPath = string.Format("~/ASP/acct_tasks/invoice_pdf.asp?InvoiceNo={0}", h.invoice_no), FileName = string.Format("INV {0}.pdf", h.invoice_no) }); } } } else//Direct Master { eitem.Attachments.Add(new EmailAttachment() { IsSelected = true, GeneratorPath = string.Format("~/ASP/acct_tasks/invoice_pdf.asp?InvoiceNo={0}", hbItems[0].invoice_no), FileName = string.Format("INV {0}.pdf", hbItems[0].invoice_no) }); } eitems.Add(eitem); } } return(eitems); }
private void OnSubmittedMessageHandler(SubmittedMessageEventSource source, QueuedMessageEventArgs e) { Logger.Debug("[GenericExchangeTransportagent] [RoutingAgent] OnSubmittedMessage fired..."); var emailItem = new EmailItem(e.MailItem); _config.RoutingAgentConfig.OnSubmittedMessage.ToList().ForEach( x => { try { x.Execute(emailItem); } catch (Exception ex) { Logger.Error(ex, @"Error Executing ""OnSubmittedMessage"""); } }); if (emailItem.ShouldBeDeletedFromQueue) { source.Delete(); } }
public async Task <IHttpActionResult> PostEmailItem(EmailItem emailItem) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } bool bSent = await SendOneEmail(emailItem); if (!bSent) { return(Ok("Failed to send email")); } return(Ok("The mail is sent successfully")); }
private Task DownloadEmailBodyAsync(EmailItem item) { return(Helper.Downloader.AddTaskToQueue(() => { item.Body = emailService.DownloadBody(item.Uid); if (SelectedItem != null && SelectedItem.Uid == item.Uid) { RenderEmailBodyToUI(item.Body); } else { DownloadFailedList.Add(item.Uid); } }, cts.Token)); }
private EmailItem CreateEmailItem(StringBuilder builder) { string[] emailTo = GetEmailAddresses(); var mailMsg = new EmailItem { From = "", Subject = "Vendor Listing", Content = "See attached report.", HtmlFormat = true, }; mailMsg.AddTo(emailTo); byte[] fileInput = Encoding.UTF8.GetBytes(builder.ToString()); mailMsg.AddAttachment(fileInput, "VendorListing.csv"); return(mailMsg); }
public ActionResult ShowMessage(string code, Dictionary <string, string> parameters) { EmailItem res = null; var msg = ""; if (code != null && parameters != null) { res = mng.ShowMessage(code, parameters, out msg); } var result = res != null; return(Json(new { result, msg, email = result ? new { res.code, res.from, res.to, caption = res.subject, body = res.template } : null })); }
private async void OnItemSelected(EmailItem item) { if (item == null) { return; } if (string.IsNullOrWhiteSpace(item.Body)) { if (DownloadFailedList.Contains(item.Uid)) { await DownloadEmailBodyAsync(item); } } else { RenderEmailBodyToUI(item.Body); } }
private async Task <bool> SendOneEmail(EmailItem item) { Response responseSendGrid = await SendSendGridMessage(item); if (responseSendGrid.StatusCode == HttpStatusCode.OK || responseSendGrid.StatusCode == HttpStatusCode.Accepted) { return(true); } IRestResponse responseMailgun = SendMailgunMessage(item); if (responseMailgun.StatusCode == HttpStatusCode.OK) { return(true); } return(false); }
protected void CreateUser_Click(object sender, EventArgs e) { var manager = Context.GetOwinContext().GetUserManager <ApplicationUserManager>(); var signInManager = Context.GetOwinContext().Get <ApplicationSignInManager>(); var user = new ApplicationUser() { UserName = Email.Text, Email = Email.Text }; IdentityResult result = manager.Create(user, Password.Text); if (result.Succeeded) { // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 string code = manager.GenerateEmailConfirmationToken(user.Id); string callbackUrl = IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id, Request); manager.SendEmail(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>."); EmailItem E = new EmailItem { Recipient = user.Email, Subect = $"{"Madden "} - {"Confirm Account"}", Message = "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>." }; try { EmailItem.SendEmail(E); } catch (Exception ex) { Console.WriteLine(ex.Message); } signInManager.SignIn(user, isPersistent: false, rememberBrowser: false); // IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else { ErrorMessage.Text = result.Errors.FirstOrDefault(); } }
protected void SendEmail(EmailItem email, EmailSettings settings, string userName, string attach = "") { var builder = new BodyBuilder(); MimeMessage mail = new MimeMessage(); mail.From.Add(new MailboxAddress(settings.DisplayName, email.from)); mail.To.Add(new MailboxAddress(email.to)); mail.Subject = email.subject; builder.HtmlBody = email.template; mail.Body = builder.ToMessageBody(); if (!string.IsNullOrWhiteSpace(email.bcc)) { mail.Bcc.AddRange(email.bcc.Split(',').Select(x => { return(new MailboxAddress(x.Trim())); })); } if (!string.IsNullOrWhiteSpace(email.cc)) { mail.Cc.AddRange(email.cc.Split(',').Select(x => { return(new MailboxAddress(x.Trim())); })); } using (var client = new MailKit.Net.Smtp.SmtpClient()) { client.Connect(settings.Host, settings.Port, settings.IsSSL); client.AuthenticationMechanisms.Remove("XOAUTH2"); //' Do not use OAUTH2 client.Authenticate(settings.UserName, settings.Password); //' Use a username / password to authenticate. client.Send(mail); client.Disconnect(true); } var log = new EmailLogItem { createdBy = _getUserName(), emailID = email.id, from = email.from, to = email.to, subject = email.subject, text = email.template, details = "" }; _logEmail(log); }
public static List <EmailItem> CheckForNewMail() { ItemView View = new ItemView(10); SearchFilter Filter = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false); List <EmailItem> EmailItems = new List <EmailItem>(); FindItemsResults <Item> SearchResults = CreateExchangeConnection().FindItems(WellKnownFolderName.Inbox, Filter, View); foreach (Item item in SearchResults.Items) { EmailMessage ItemEmail = item as EmailMessage; EmailItem NewEmailItem = new EmailItem(); NewEmailItem.From = ItemEmail.Sender.Name; NewEmailItem.Subject = ItemEmail.Subject; NewEmailItem.ReceivedTimestamp = ItemEmail.DateTimeReceived; EmailItems.Add(NewEmailItem); } return(EmailItems); }
public bool CreateNewMail(EmailItem email, out string msg) { bool res; msg = ""; try { if (!_hasAccessToCRUD(CRUDOperationType.create)) { throw new Exception("Недостаточный уровень доступа!"); } _createNewMail(email); res = true; } catch (Exception e) { msg = "Ошибка при создании шаблона письма!\n" + e.ToString(); res = false; } return(res); }
private void OnSubmittedMessageHandler(SubmittedMessageEventSource source, QueuedMessageEventArgs e) { Logger.Debug("[GenericTransportAgent] RoutingAgent - OnSubmittedMessage fired..."); var emailItem = new EmailItem(e.MailItem); foreach (var x in Configuration.Config.RoutingAgentConfig.OnSubmittedMessage) { try { x.Execute(emailItem); } catch (Exception ex) { Logger.Error(ex, @"Error Executing ""OnSubmittedMessage"""); } } if (emailItem.ShouldBeDeletedFromQueue) { source.Delete(); } }
InputItem pick_next_PdfItem(System.Collections.IEnumerator items_ennumerator) { lock (emails2sent_time) { int delay = Settings.Email.MinRandomDelayMss + (int)((float)(Settings.Email.MaxRandomDelayMss - Settings.Email.MinRandomDelayMss) * random.NextDouble()); TimeSpan min_wait_period = TimeSpan.MaxValue; EmailItem min_wait_period_ei = null; for (items_ennumerator.Reset(); items_ennumerator.MoveNext();) { EmailItem ei = ((EmailItem)items_ennumerator.Current); string to_email = ei.Data.ListAgentEmail; DateTime sent_time; if (!emails2sent_time.TryGetValue(to_email, out sent_time)) { emails2sent_time[to_email] = DateTime.Now; return(ei); } TimeSpan wait_period = sent_time.AddMilliseconds(delay) - DateTime.Now; if (wait_period < TimeSpan.FromSeconds(0)) { emails2sent_time[to_email] = DateTime.Now; return(ei); } if (wait_period > min_wait_period) { min_wait_period = wait_period; min_wait_period_ei = ei; } } if (min_wait_period_ei != null && Session.GetInputItemQueue <DataItem>().CountOfNew < 1) { Thread.Sleep(min_wait_period); emails2sent_time[min_wait_period_ei.Data.ListAgentEmail] = DateTime.Now; return(min_wait_period_ei); } return(null); } }
protected void Forgot(object sender, EventArgs e) { if (IsValid) { // Validate the user's email address var manager = Context.GetOwinContext().GetUserManager <ApplicationUserManager>(); ApplicationUser user = manager.FindByName(Email.Text); if (user == null || !manager.IsEmailConfirmed(user.Id)) { FailureText.Text = "The user either does not exist or is not confirmed."; ErrorMessage.Visible = true; return; } // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send email with the code and the redirect to reset password page string code = manager.GeneratePasswordResetToken(user.Id); string callbackUrl = IdentityHelper.GetResetPasswordRedirectUrl(code, Request); manager.SendEmail(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>."); EmailItem E = new EmailItem(); E.Recipient = user.Email; E.Subect = string.Format("{0} - {1}", "Madden ", "Reset Password"); E.Message = "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>."; try { EmailItem.SendEmail(E); } catch (Exception ex) { Console.WriteLine(ex.Message); } loginForm.Visible = false; DisplayEmail.Visible = true; } }
public async Task SendEmailAsync(EmailItem emailItem) { string apiKey = _configuration[ConfigurationKey.Email.SendGrid.APIKey]; var client = new SendGridClient(apiKey); EmailAddress fromEmailAddress = new EmailAddress("[email protected] ", "Fortifex"); EmailAddress replyEmailAddress = new EmailAddress("[email protected] ", "Fortifex"); EmailAddress toEmailAddress = new EmailAddress(emailItem.ToAdress); var message = new SendGridMessage() { From = fromEmailAddress, ReplyTo = replyEmailAddress, Subject = emailItem.Subject, PlainTextContent = emailItem.Body, HtmlContent = emailItem.Body }; message.AddTo(toEmailAddress); await client.SendEmailAsync(message); }
public async Task SendEmail(EmailItem email) { var sendRequest = new SendEmailRequest { Source = await GetSenderAddress(), Destination = new Destination { ToAddresses = await GetToAddresses() }, Message = new Message { Subject = new Content(email.Subject), Body = new Body { Html = new Content { Charset = "UTF-8", Data = email.HtmlBody }, Text = new Content { Charset = "UTF-8", Data = email.TextBody } } } }; try { Console.WriteLine("Sending email using SES"); Console.WriteLine("Successfully sent"); } catch (Exception ex) { Console.WriteLine("Failed to send: " + ex); } }
static async Task <Response> SendSendGridMessage(EmailItem item) { var apiKey = "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"; var client = new SendGridClient(apiKey); var msg = new SendGridMessage() { From = new EmailAddress("*****@*****.**", "Testing"), Subject = (String.IsNullOrEmpty(item.Subject) ? "Hello" : item.Subject), PlainTextContent = (String.IsNullOrEmpty(item.Contents) ? "Congratulations! You have just sent an email!" : item.Contents) }; msg.AddTo(new EmailAddress(item.EmailTO, item.EmailTO)); if (!String.IsNullOrEmpty(item.EmailCC)) { msg.AddCc(new EmailAddress(item.EmailCC, item.EmailCC)); } if (!String.IsNullOrEmpty(item.EmailBCC)) { msg.AddBcc(new EmailAddress(item.EmailBCC, item.EmailBCC)); } Response response = await client.SendEmailAsync(msg); return(response); }