示例#1
0
        SendGridMessage CreateMessage(string title, string text, string from, IEnumerable <string> to, IEnumerable <string> cc = null, IEnumerable <string> bcc = null, string mimeType = null
                                      , IEnumerable <Attachment> files = null)
        {
            var message = new SendGridMessage();

            from = from ?? info.DefaultFromAddress;
            message.SetFrom(new EmailAddress(from));

            string[] toList = to?.Where(t => !string.IsNullOrWhiteSpace(t)).ToArray();

            if (toList != null && toList.Any())
            {
                message.AddTos(toList.Select(m => new EmailAddress(m)).ToList());
            }
            else
            {
                message.AddTos(new List <EmailAddress>()
                {
                    new EmailAddress(info.DefaultToAddress)
                });
            }

            if (cc != null && cc.Any())
            {
                message.AddTos(cc.Select(m => new EmailAddress(m)).ToList());
            }

            if (bcc != null && bcc.Any())
            {
                message.AddTos(bcc.Select(m => new EmailAddress(m)).ToList());
            }

            if (files != null && files.Any())
            {
                message.Attachments = files.ToList();
                //var attachList = files.Select(m => new Attachment()
                //{
                //    Content = Convert.ToBase64String(m.ReadAllBytes())
                //    //Type = "image/png",
                //    //Filename = "banner2.png",
                //    //Disposition = "inline",
                //    //ContentId = "Banner 2"
                //}).ToList();
            }

            message.SetSubject(title);

            if (string.IsNullOrEmpty(mimeType))
            {
                mimeType = MimeType.Text;
            }

            message.AddContent(MimeType.Text, text);
            return(message);
        }
        public async Task <Response> sendConfirmationEmail(string email, string name, int id)
        {
            var msg = new SendGridMessage();

            msg.SetFrom(new EmailAddress("*****@*****.**", "MSSA"));

            var recipients = new List <EmailAddress>();

            recipients.Add(new EmailAddress(email, name));
            msg.AddTos(recipients);

            msg.SetTemplateId("d-3f737b74633140dd853760238bcb6a8f");

            var dynamicTemplateData = new UserInfo
            {
                Name  = name,
                Email = email,
                Id    = id
            };

            msg.SetTemplateData(dynamicTemplateData);

            var      client   = new SendGridClient(APIKey);
            Response response = await client.SendEmailAsync(msg);

            return(response);
        }
示例#3
0
        public async Task EmailJoke(JokeToEmail joke, List <ToEmailAddress> toEmails)
        {
            var client = new SendGridClient(_config["SendGridKey"]);
            var msg    = new SendGridMessage();

            msg.SetFrom(new EmailAddress(_config["ReturnEmail"], "Juan\'s Jokes"));

            var emails = new List <EmailAddress>();

            toEmails.ForEach(r =>
            {
                emails.Add(new EmailAddress(r.Email, r.Name));
            });

            msg.AddTos(emails);

            msg.SetSubject("Juan has a new joke for you");

            var imageName = PhotoRandomizer.GetRandomJuanImage();
            var builder   = new StringBuilder();

            builder.Append($"<h1>{joke.Text}</h1><br/><br/>{joke.Punchline}");
            builder.Append("<br/><br/>");
            builder.Append("<img src=\"https://teamcatalyst.azurewebsites.net/images/" + imageName + "\" width=\"200\" height=\"160\">");
            builder.Append("<br/><br/>");
            var siteUrl = _config["SiteUrl"];

            builder.Append($"<p><small>For more jokes visit the <a href=\"{siteUrl}\">Jokes Site</a>.</small></p>");

            //msg.AddContent(MimeType.Text, message);
            msg.AddContent(MimeType.Html, builder.ToString());

            await client.SendEmailAsync(msg);
        }
示例#4
0
        public static async Task <string> SendAsync(string apiKey, string recipients, string email, string subject, string message)
        {
            try
            {
                List <EmailAddress> emails = new List <EmailAddress>();
                foreach (string s in recipients.Split(new char[] { ';' }))
                {
                    emails.Add(new EmailAddress(s));
                }
                var client = new SendGridClient(apiKey);
                var msg    = new SendGridMessage()
                {
                    From             = new EmailAddress("*****@*****.**", "trndx mailer"),
                    Subject          = $"Contact Form - {subject.Trim()}",
                    PlainTextContent = $"{message.Trim()} - sent from {email}",
                    HtmlContent      = $"{message.Trim()} - sent from {email}"
                };
                msg.AddTos(emails);
                var response = await client.SendEmailAsync(msg);

                return(response.StatusCode.ToString() + ":" + response.Headers.ToString());
            }
            catch (Exception e)
            {
                return(e.ToString());
            }
        }
示例#5
0
        /// <summary>
        /// Send a single simple email to multiple recipients with option for displaying all the recipients present in "To" section of email
        /// </summary>
        /// <param name="from">An email object that may contain the recipient’s name, but must always contain the sender’s email.</param>
        /// <param name="tos">A list of email objects that may contain the recipient’s name, but must always contain the recipient’s email.</param>
        /// <param name="subject">The subject of your email. This may be overridden by SetGlobalSubject().</param>
        /// <param name="plainTextContent">The text/plain content of the email body.</param>
        /// <param name="htmlContent">The text/html content of the email body.</param>
        /// <param name="showAllRecipients">Displays all the recipients present in the "To" section of email.The default value is false</param>
        /// <returns>A SendGridMessage object.</returns>
        public static SendGridMessage CreateSingleEmailToMultipleRecipients(
            EmailAddress from,
            List <EmailAddress> tos,
            string subject,
            string plainTextContent,
            string htmlContent,
            bool showAllRecipients = false)
        {
            var msg = new SendGridMessage();

            if (showAllRecipients)
            {
                msg.SetFrom(from);
                msg.SetGlobalSubject(subject);
                if (!string.IsNullOrEmpty(plainTextContent))
                {
                    msg.AddContent(MimeType.Text, plainTextContent);
                }

                if (!string.IsNullOrEmpty(htmlContent))
                {
                    msg.AddContent(MimeType.Html, htmlContent);
                }

                msg.AddTos(tos);
            }
            else
            {
                msg = CreateSingleEmailToMultipleRecipients(from, tos, subject, plainTextContent, htmlContent);
            }

            return(msg);
        }
示例#6
0
        public override async Task <string> SendEmailAsync()
        {
            try
            {
                var apiKey    = SendGridApiKey;
                var fromEmail = new EmailAddress(FromAddress);
                var client    = new SendGridClient(apiKey);
                var message   = new SendGridMessage();
                message.AddTos(GenerateEmailAddress(To));
                message.From = fromEmail;
                message.AddHeader("recover", "Account Recovery");
                message.Subject     = Subject;
                message.HtmlContent = Body;
                Response response = await client.SendEmailAsync(message);

                if (response.StatusCode == System.Net.HttpStatusCode.OK || response.StatusCode == System.Net.HttpStatusCode.Accepted)
                {
                    return("success");
                }
            }
            catch (Exception ex)
            {
                _logger.Error("error in SendEmailAsync", ex);
            }
            return("fail");
        }
        private async Task SendEmailAsync(
            Func <string> subjectBuilder,
            Func <string> contentBuilder,
            CancellationToken cancellationToken = default)
        {
            var msg = new SendGridMessage();

            msg.SetFrom(new EmailAddress(this.options.Mail.FromEmail, "Marketplace command center"));

            var recipients = new List <EmailAddress> {
                new EmailAddress(this.options.Mail.OperationsTeamEmail)
            };

            msg.AddTos(recipients);

            msg.SetSubject(subjectBuilder());

            msg.AddContent(MimeType.Html, contentBuilder());

            var client   = new SendGridClient(this.options.Mail.ApiKey);
            var response = await client.SendEmailAsync(msg, cancellationToken).ConfigureAwait(false);

            if ((response.StatusCode != System.Net.HttpStatusCode.OK) &&
                (response.StatusCode != System.Net.HttpStatusCode.Accepted))
            {
                throw new ApplicationException(await response.Body.ReadAsStringAsync(cancellationToken).ConfigureAwait(false));
            }
        }
示例#8
0
        private async Task SendEmail(string email, string subject, string message)
        {
            var msg = new SendGridMessage();

            msg.SetFrom(new EmailAddress(_sendgrid.SenderEmail, _sendgrid.SenderName));

            var emails = new List <EmailAddress>();

            if (!string.IsNullOrEmpty(_sendgrid.ReceiveEmail))
            {
                emails.Add(new EmailAddress(_sendgrid.ReceiveEmail));
            }
            else
            {
                emails.Add(new EmailAddress(email));
            }

            msg.AddTos(emails);
            var sujecttxt = $"{_sendgrid.SubjectPrefix}{subject}";

            msg.SetSubject(sujecttxt);
            msg.AddContent(MimeType.Html, message);

            var client = new SendGridClient(_sendgrid.ApiKey);

            var response = await client.SendEmailAsync(msg);

            var emailstxt = string.Join(";", emails.Select(x => string.IsNullOrEmpty(x.Name) ? $"{x.Email}" : $"{x.Email}<{x.Name}>"));

            _log.LogInformation($"Email Subject={sujecttxt} To={emailstxt} Response={response.StatusCode} {message}");
        }
示例#9
0
        private static async Task  SendEmail(string blobData)
        {
            //Declare Mail object
            var msg = new SendGridMessage();

            msg.SetFrom(new EmailAddress("*****@*****.**", "SendGrid AIP Team"));

            var recipients = new List <EmailAddress>
            {
                new EmailAddress("*****@*****.**", "Sarfraz Malik"),
                new EmailAddress("*****@*****.**", "Sarfraz Malik Gmail"),
            };

            msg.AddTos(recipients);

            msg.SetSubject("A New Blob file was added");

            msg.AddContent(MimeType.Text, "The blob file data is " + blobData);

            var apiKey = System.Environment.GetEnvironmentVariable("SENDGRID_APIKEY");
            var client = new SendGridClient(apiKey);

            // Send
            var response = await client.SendEmailAsync(msg);
        }
        public static async Task <HttpStatusCode> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");

            var apiKey = System.Environment.GetEnvironmentVariable("SEND_GRID_API_KEY");
            var client = new SendGridClient(apiKey);
            var msg    = new SendGridMessage();

            msg.SetFrom(new EmailAddress("*****@*****.**", "Razfilms Contact Form"));

            var recipients = new List <EmailAddress>
            {
                new EmailAddress("*****@*****.**", "Robert Zimmerman"),
            };

            msg.AddTos(recipients);

            msg.SetSubject("Thanks for contacting Razfilms");

            msg.AddContent(MimeType.Text, "Hello World plain text!");
            msg.AddContent(MimeType.Html, "<p>Hello World!</p>");
            string  requestBody = new StreamReader(req.Body).ReadToEnd();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);
            //name = name ?? data?.name;
            var response = await client.SendEmailAsync(msg);

            return(response.StatusCode);
            //? (ActionResult)new OkObjectResult($"Hello, {name}")
            //: new BadRequestObjectResult("Please pass a name on the query string or in the request body");
        }
示例#11
0
        public async Task <string> Save(string apiKey, string recipients, string message)
        {
            try
            {
                List <EmailAddress> emails = new List <EmailAddress>();
                foreach (string s in recipients.Split(new char[] { ';' }))
                {
                    emails.Add(new EmailAddress(s));
                }
                var client = new SendGridClient(apiKey);
                var msg    = new SendGridMessage()
                {
                    From             = new EmailAddress("*****@*****.**", "S'way Admin"),
                    Subject          = "S'way Exchange User Feedback",
                    PlainTextContent = "Feedback: " + message,
                    HtmlContent      = "<strong>Feedback: </strong><i>" + message + "</i>"
                };
                msg.AddTos(emails);
                var response = await client.SendEmailAsync(msg);

                return(response.StatusCode.ToString() + ":" + response.Headers.ToString());
            }
            catch (Exception e)
            {
                return(e.ToString());
            }
        }
示例#12
0
        static async Task SendEmail(Account account, int passcode)
        {
            var apiKey = System.Environment.GetEnvironmentVariable("SENDGRID_WEB_API");
            var client = new SendGridClient(apiKey);

            var msg = new SendGridMessage();

            msg.SetFrom(new EmailAddress("*****@*****.**", "TRIOS Capstone"));

            var recipients = new List <EmailAddress>
            {
                new EmailAddress(account.emailID, account.firstName + ' ' + account.lastName),
            };

            msg.AddTos(recipients);

            msg.SetSubject("Passcode for Registration");

            string content = $"<p>Hello {account.firstName } {account.lastName},</p>" +
                             $"<br><p>Please use {passcode} as a passcode for registration.</p>" +
                             $"<br><p>Thank you...</p>" +
                             $"<br><h3>TRIOS Capstone Team</h3>";

            //msg.AddContent(MimeType.Text, "Hello World plain text!");
            msg.AddContent(MimeType.Html, content);

            var response = await client.SendEmailAsync(msg);
        }
        public static SendGridMessage ToSendGridMessage(this MailMessageDto dto)
        {
            if (dto.Sender != null)
            {
                throw new NotSupportedException("Sender header is not supported by SendGrid.");
            }
            if ((dto.ReplyTo?.Count ?? 0) > 1)
            {
                throw new NotSupportedException("Only one Reply-To header is supported by SendGrid.");
            }

            var msg = new SendGridMessage();

            // Add standard header fields
            msg.From = dto.From.ToEmailAddress();
            if (dto.To.Any())
            {
                msg.AddTos(dto.To.ToEmailAddress());
            }
            if (dto.Cc.Any())
            {
                msg.AddCcs(dto.Cc.ToEmailAddress());
            }
            if (dto.Bcc.Any())
            {
                msg.AddBccs(dto.Bcc.ToEmailAddress());
            }
            msg.ReplyTo = dto.ReplyTo.FirstOrDefault().ToEmailAddress();
            msg.Subject = dto.Subject;

            // Add custom header fields
            foreach (var item in dto.CustomHeaders)
            {
                msg.Headers.Add(item.Key, item.Value);
            }

            // Construct body
            if (!string.IsNullOrWhiteSpace(dto.BodyText))
            {
                msg.PlainTextContent = dto.BodyText;
            }
            if (!string.IsNullOrWhiteSpace(dto.BodyHtml))
            {
                msg.HtmlContent = dto.BodyHtml;
            }

            // Add attachments
            foreach (var item in dto.Attachments)
            {
                // Get stream as byte array
                var data = new byte[item.Stream.Length];
                item.Stream.Read(data, 0, (int)item.Stream.Length);

                // Base64 encode
                var encodedData = Convert.ToBase64String(data, 0, data.Length);
                msg.AddAttachment(item.Name, encodedData, item.MimeType);
            }

            return(msg);
        }
        public async Task ConfirmEvent([ActivityTrigger] ActivateEventSendMail activateSendMail,
                                       [SendGrid(ApiKey = "SendGridConnections:ApiKey")] IAsyncCollector <SendGridMessage> messageCollector,
                                       ILogger log)
        {
            var             eventData = activateSendMail.Data;
            SendGridMessage message   = new SendGridMessage();

            message.SetFrom(new EmailAddress(sendGridSettings.From));
            message.AddTos(adminSettings.GetMails().Select(x => new EmailAddress(x)).ToList());
            message.SetSubject($"New Event submitted: {eventData.Name}");
            message.SetTemplateId(sendGridSettings.TemplateEventId);
            message.SetTemplateData(new MailEventTemplateData
            {
                confirmurl         = adminSettings.GetConfirmationEventLink(activateSendMail.InstanceId, true),
                aborturl           = adminSettings.GetConfirmationEventLink(activateSendMail.InstanceId, false),
                eventname          = eventData.Name,
                eventstartdate     = eventData.StartDate,
                eventenddate       = eventData.EndDate,
                eventbuyticket     = eventData.BuyTicket?.ToString(),
                eventcfpurl        = eventData.CFP?.Url,
                eventcfpstartdate  = eventData.CFP?.StartDate,
                eventcfpstartend   = eventData.CFP?.EndDate,
                eventcommunityname = eventData.CommunityName
            });
            await messageCollector.AddAsync(message);
        }
示例#15
0
        public static string SendEmails([ActivityTrigger] string name, ILogger log)
        {
            //TODO
            var msg = new SendGridMessage();

            msg.SetFrom(new EmailAddress("*****@*****.**", "SendGrid Test From APp"));

            var recipients = new List <EmailAddress>
            {
                new EmailAddress("*****@*****.**", "Jane Doe"),
                new EmailAddress("*****@*****.**", "Anna Lidman"),
                new EmailAddress("*****@*****.**", "Peter Saddow")
            };

            msg.AddTos(recipients);

            msg.SetSubject("Testing the SendGrid C# Library");

            msg.AddContent(MimeType.Text, "Hello World plain text!");
            msg.AddContent(MimeType.Html, "<p>Hello World!</p>");



            log.LogInformation($"Saying hello to {name}.");
            return($"Hello {name}!");
        }
示例#16
0
        public async Task <bool> SendPaymentConfirmedAsync(List <EmailAddress> emailsTo)
        {
            var apiKey = Settings.Settings.SendgridKey;
            var client = new SendGridClient(apiKey);
            var msg    = new SendGridMessage();

            msg.SetFrom(new EmailAddress("*****@*****.**", "SoftLuv"));

            var recipients = emailsTo;

            msg.AddTos(recipients);

            msg.SetSubject("Pagamento confirmado :)");

            msg.AddContent(MimeType.Text, "Olá :)");
            msg.AddContent(MimeType.Html, "<p>Percebemos que você confirmou nosso pagamento, agradecemos, e continue indicando!</p>");
            var response = await client.SendEmailAsync(msg);

            _logger.LogInformation($"{DateTime.Now:hh:mm:ss} Send mail to notify, response is: {response.StatusCode}");
            if (response.StatusCode == System.Net.HttpStatusCode.Accepted)
            {
                return(true);
            }
            return(false);
        }
示例#17
0
        private static async Task Execute()
        {
            var apiKey = "<api-key>";
            var client = new SendGridClient(apiKey);
            var msg    = new SendGridMessage();

            msg.SetFrom(new EmailAddress("*****@*****.**"));
            msg.AddTo(new EmailAddress("*****@*****.**", "Ashirwad"));

            var to_emails = new List <EmailAddress>
            {
                new EmailAddress("*****@*****.**", "test 1")
            };

            msg.AddTos(to_emails);

            msg.SetTemplateId("d-3e97f42b3efc437cb23f754664d41fca");

            var dynamicTemplateData = new ExampleTemplateData
            {
                Subject = "100DaysOfServerlessCode",
            };

            msg.SetTemplateData(dynamicTemplateData);
            var response = await client.SendEmailAsync(msg);
        }
        public async Task SendEmailAsync(Mail mail)
        {
            var sendGridClient = new SendGridClient(_sendGridOptions.APIKey);

            var sendGridMessage = new SendGridMessage();

            sendGridMessage.From = new EmailAddress(mail.From);

            sendGridMessage.AddTos(mail.To.Select(x => new EmailAddress(x)).ToList());

            if (mail.CC != null)
            {
                sendGridMessage.AddCcs(mail.CC.Select(x => new EmailAddress(x)).ToList());
            }

            if (mail.BCC != null)
            {
                sendGridMessage.AddBccs(mail.BCC.Select(x => new EmailAddress(x)).ToList());
            }

            sendGridMessage.Subject = mail.Subject;

            if (mail.IsBodyHTML)
            {
                sendGridMessage.HtmlContent = mail.Body;
            }

            else
            {
                sendGridMessage.PlainTextContent = mail.Body;
            }

            await sendGridClient.SendEmailAsync(sendGridMessage);
        }
        public EmailResponse Send(EmailContract contract)
        {
            var emailMessage = new SendGridMessage()
            {
                From        = new EmailAddress(contract.FromEmailAddress, contract.Alias),
                Subject     = contract.Subject,
                HtmlContent = contract.Body
            };
            List <EmailAddress> toEmails = new List <EmailAddress>();

            contract.ToEmailAddress.ForEach(s => toEmails.Add(new EmailAddress(s)));

            emailMessage.AddTos(toEmails);
            if (!string.IsNullOrWhiteSpace(contract.BccEmailAddress))
            {
                emailMessage.AddBcc(new EmailAddress(contract.BccEmailAddress));
            }

            if (!string.IsNullOrWhiteSpace(contract.CcEmailAddress))
            {
                emailMessage.AddBcc(new EmailAddress(contract.CcEmailAddress));
            }

            return(ProcessResponse(_client.SendEmailAsync(emailMessage).Result));
        }
示例#20
0
        public async Task Send(string from, string name, string subject, EmailAddress to, string content)
        {
            var msg = new SendGridMessage();

            msg.SetFrom(new EmailAddress(from, name));
            var recipients = new List <EmailAddress> {
                to
            };

            msg.AddTos(recipients);
            msg.SetSubject(subject);
            msg.HtmlContent = content;
//            string apiKey = "";
//#if DEBUG
//            apiKey = Configuration.SendGridApiKey;
//#else
//            apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY");
//#endif
            var client = new SendGridClient(key);

            try
            {
                var response = await client.SendEmailAsync(msg);
            }
            catch (Exception e)
            {
            }
        }
示例#21
0
        public ActionResult CreateAccreditMessagePost(AccreditFormViewModel AccreditMessage)
        {
            if (!ModelState.IsValid)
            {
                return(CurrentUmbracoPage());
            }

            ViewBag.Accredit = AccreditMessage;

            var apiKey = WebConfigurationManager.AppSettings["SENDGRID_APIKEY"];
            var client = new SendGridClient(apiKey);

            var msg = new SendGridMessage();

            msg.SetFrom(new EmailAddress(AccreditMessage.EmailAddress));
            var recipients = new List <EmailAddress>
            {
                new EmailAddress(WebConfigurationManager.AppSettings["contactEmailAddress"])
            };

            msg.AddTos(recipients);
            msg.SetSubject("Akkreditiontihakemus: " + AccreditMessage.FirstName + " " + AccreditMessage.LastName);
            msg.AddContent(MimeType.Html, BuildAccreditEmail(AccreditMessage));

            try
            {
                var response = client.SendEmailAsync(msg);
            }
            catch (Exception e)
            {
                throw e.InnerException;
            }

            return(CurrentUmbracoPage());
        }
        public async Task SendCoachNotificationEmail(IdentityMessage message, string from, string fromName, List <EmailAddress> tos, HttpPostedFileBase postFile)
        {
            var myMessage = new SendGridMessage();

            //myMessage.From = new EmailAddress(from, fromName);
            myMessage.From             = new EmailAddress("*****@*****.**", "Administrator");
            myMessage.Subject          = message.Subject;
            myMessage.PlainTextContent = message.Body;
            myMessage.HtmlContent      = $@"
            Hi
            <br/>
            {message.Body} <br/>
             <br/>
             <br/>
            Best Regards, <br/>
            Vibrant your body <br/>
            55 King Rd Autumn, VIC,9999 <br/>
            012345678<br/>
            <img src=http://cdn.mcauto-images-production.sendgrid.net/7d8250131a038040/684a1fec-03be-4dd8-b957-446d7e2cf5c6/569x320.jpg  width='200'>";

            myMessage.AddTos(tos);
            if (postFile != null)
            {
                await myMessage.AddAttachmentAsync(postFile.FileName, postFile.InputStream);
            }
            var apiKey   = ConfigurationManager.AppSettings["SendGridApi"];
            var client   = new SendGridClient(apiKey);
            var response = await client.SendEmailAsync(myMessage);

            Console.WriteLine(response.Body);
        }
        public void send(String toEmail, String messageSubject,
                         String messageBody, String fullPath, String fileName)
        {
            string[] emailAddresses = toEmail.Split(',');
            var      client         = new SendGridClient(API_KEY);
            var      to_emails      = new List <EmailAddress>();

            for (int i = 0; i < emailAddresses.Length; i++)
            {
                to_emails.Add(new EmailAddress(emailAddresses[i], "User"));
            }
            ;
            var msg = new SendGridMessage();

            msg.SetFrom("*****@*****.**", "FIT5032 BULK EMAIL");
            var plainTextContent = messageBody;
            var htmlContent      = "<p>" + messageBody + "</p>";

            msg.PlainTextContent = plainTextContent;
            msg.Subject          = messageSubject;
            msg.AddTos(to_emails);

            if (fullPath == "nothing")
            {
                //msg.AddAttachment(model.AttachedFile.FileName, file);
                var response = client.SendEmailAsync(msg);
            }
            else
            {
                var bytes = System.IO.File.ReadAllBytes(fullPath);
                var file  = Convert.ToBase64String(bytes);
                msg.AddAttachment(fileName, file);
                var response = client.SendEmailAsync(msg);
            }
        }
示例#24
0
        private static async Task SendEmail(string email, string subject, JObject data)
        {
            var client = new SendGridClient(
                ConfigurationManager.AppSettings["SendGridApiKey"]);

            var msg = new SendGridMessage();

            msg.SetFrom(new EmailAddress(
                            ConfigurationManager.AppSettings["EmailFrom"]));

            var recipients = new List <EmailAddress> {
                new EmailAddress(email)
            };

            msg.AddTos(recipients);

            msg.SetSubject(subject);

            msg.AddAttachment("Event.json",
                              ToBase64(data.ToString(Formatting.Indented)), "application/json");

            msg.AddContent(MimeType.Text, data.ToString(Formatting.None));

            var response = await client.SendEmailAsync(msg);
        }
示例#25
0
        //static Logger.Info infoLogger = new Logger.Info();
        // static Logger.Error errorLogger = new Logger.Error();
        public static async Task <bool> SendAsync(MailModel model, SendGridClient client)
        {
            try
            {
                var message = new SendGridMessage();
                message.SetFrom(new EmailAddress(model.MailFrom));

                var recipients = new List <EmailAddress>();
                foreach (var item in model.MailTo)
                {
                    recipients.Add(new EmailAddress(item));
                }
                message.AddTos(recipients);
                message.SetSubject(model.Title);
                message.AddContent(MimeType.Text, model.Body);

                var response = await client.SendEmailAsync(message);

                return(true);
            }
            catch (SmtpException smtpEx)
            {
                //errorLogger.Log($"Smtp Error: {smtpEx.Message}");
                throw;
            }
            catch (Exception ex)
            {
                //errorLogger.Log(ex.Message);
                throw;
            }
        }
示例#26
0
        internal async Task SendEmail(string toemail, string body, string plainTextMessage)
        {
            try
            {
                var msg = new SendGridMessage()
                {
                    From             = new EmailAddress(_fromEmail, _fromEmailName),
                    Subject          = _subject,
                    HtmlContent      = body,
                    PlainTextContent = plainTextMessage
                };

                var toEmailsList = _additionalToEmails.Select(toEmail => new EmailAddress(toEmail)).ToList();
                toEmailsList.Add(new EmailAddress(toemail));
                msg.AddTos(toEmailsList);

                var ccEmailsList = _ccEmails.Select(x => new EmailAddress(x)).ToList();
                msg.AddCcs(ccEmailsList);

                var response = await _client.SendEmailAsync(msg);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
            }
        }
示例#27
0
        public async Task SendEmailAsync(MailMessage message)
        {
            var sendGridMessage = new SendGridMessage
            {
                Subject          = message.Subject,
                From             = new EmailAddress(_globalSettings.Mail.ReplyToEmail, _globalSettings.SiteName),
                HtmlContent      = message.HtmlContent,
                PlainTextContent = message.TextContent
            };

            sendGridMessage.SetClickTracking(true, false);
            sendGridMessage.SetOpenTracking(true, null);
            sendGridMessage.AddTos(message.ToEmails.Select(e => new EmailAddress(e)).ToList());
            if (message.BccEmails?.Any() ?? false)
            {
                sendGridMessage.AddBccs(message.BccEmails.Select(e => new EmailAddress(e)).ToList());
            }

            if (message.MetaData?.ContainsKey("SendGridTemplateId") ?? false)
            {
                sendGridMessage.HtmlContent      = " ";
                sendGridMessage.PlainTextContent = " ";
                sendGridMessage.TemplateId       = message.MetaData["SendGridTemplateId"].ToString();
            }

            if (message.MetaData?.ContainsKey("SendGridSubstitutions") ?? false)
            {
                var subs = message.MetaData["SendGridSubstitutions"] as Dictionary <string, string>;
                sendGridMessage.AddSubstitutions(subs);
            }

            var cats = new List <string> {
                "ByteGarden Server"
            };

            if (!string.IsNullOrWhiteSpace(message.Category))
            {
                cats.Add(message.Category);
            }
            sendGridMessage.AddCategories(cats);

            if (message.MetaData?.ContainsKey("SendGridBypassListManagement") ?? false)
            {
                var bypass = message.MetaData["SendGridBypassListManagement"] as bool?;
                sendGridMessage.SetBypassListManagement(bypass.GetValueOrDefault(false));
            }

            try
            {
                await SendAsync(sendGridMessage, false);
            }
            catch (HttpRequestException)
            {
                await SendAsync(sendGridMessage, true);
            }
            catch (WebException)
            {
                await SendAsync(sendGridMessage, true);
            }
        }
        public async Task <IHttpActionResult> SendEmail(EmailRequest request)
        {
            try
            {
                var msg = new SendGridMessage();

                msg.SetFrom(new EmailAddress("*****@*****.**", "Pat Alburtus"));

                var recipients = new List <EmailAddress>
                {
                    new EmailAddress(request.RecipientEmailAddress, request.RecipientName)
                };

                msg.AddTos(recipients);

                msg.SetSubject(request.Subject);

                msg.AddContent(MimeType.Text, request.Body);

                var client  = new SendGridClient(API_KEY);
                var respone = await client.SendEmailAsync(msg);

                return(Ok(respone.StatusCode + ": " + respone.Body));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
示例#29
0
        private static async Task Main()
        {
            var msg = new SendGridMessage();

            msg.SetFrom(new EmailAddress("*****@*****.**", "Neo Ho"));

            var recipients = new List <EmailAddress>
            {
                new EmailAddress("neofelisho@gmail", "Neo Ho"),
                //new EmailAddress("*****@*****.**", "Anna Lidman"),
                //new EmailAddress("*****@*****.**", "Peter Saddow")
            };

            msg.AddTos(recipients);

            msg.SetSubject("Message from Neo Ho through SendGrid");

            msg.AddContent(MimeType.Text, "Hello World plain text!");
            msg.AddContent(MimeType.Html, "<p>Hello World!</p>");

            var builder = new ConfigurationBuilder()
                          .SetBasePath(Path.Combine(AppContext.BaseDirectory, string.Format("..{0}..{0}..{0}", Path.DirectorySeparatorChar)))
                          .AddJsonFile("appsettings.json");
            var apiKey = builder.Build().GetSection("SENDGRID_API_KEY").Value;

            var client   = new SendGridClient(apiKey);
            var response = await client.SendEmailAsync(msg);

            Console.WriteLine(response.StatusCode);
            Console.Read();
        }
示例#30
0
        public async Task <Response> SendNotification(string emailAddress)
        {
            var ticket = new TicketDTO()
            {
                CreatedDate = DateTime.Now,
                Description = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut fringilla ex sem, et mollis ante pretium varius. In non justo eu ipsum finibus rutrum at in libero. Etiam pretium augue vel luctus malesuada. Donec tempus congue nisi eu lobortis. Morbi auctor, velit vel elementum hendrerit, ligula nulla congue nisl, sed blandit nibh magna eu nunc. Duis ultricies mi sed turpis hendrerit aliquam. Proin egestas orci rhoncus commodo eleifend. Cras sed massa ac urna sollicitudin varius a ut nunc. Praesent vestibulum, metus et viverra lobortis, elit nunc rutrum erat, ut consectetur sapien dui vel ipsum. Nulla sodales leo quis venenatis congue. Pellentesque urna leo, pulvinar in arcu a, egestas sollicitudin ipsum. Duis sodales vel metus eget dapibus. Aliquam ultrices finibus nulla ut aliquam. Nam laoreet eros ac ullamcorper bibendum. Proin sed mollis orci, ut pretium est. Nullam vel faucibus neque. Pellentesque auctor velit lectus, at dictum urna iaculis at. Aliquam vehicula commodo velit ac posuere. Praesent porttitor nisl arcu, tempor gravida leo fermentum et. Morbi auctor urna sit amet interdum rhoncus. Proin ac augue porttitor, laoreet risus et, sollicitudin elit. Maecenas semper risus in iaculis efficitur. Nunc ultricies vestibulum turpis in mollis. Aenean ultricies mi quam, at ultricies tellus venenatis non. Suspendisse nec velit ac est dictum volutpat non luctus orci. Cras non odio eu velit imperdiet fermentum. Cras elementum erat at lectus cursus, id rutrum lorem eleifend. Quisque nec nulla sed lectus dapibus efficitur. Ut euismod vestibulum nibh vitae feugiat. Suspendisse potenti.",
                Name        = "Typical Ticket"
            };

            var client = new SendGridClient(apiKey);
            var msg    = new SendGridMessage();

            msg.SetFrom(new EmailAddress("*****@*****.**", "Grievance Team"));

            var recipients = new List <EmailAddress>
            {
                new EmailAddress("*****@*****.**", "Mosa Qhalane")
            };

            msg.AddTos(recipients);
            msg.SetSubject("Grievance: Email Notification");

            var emailBody = Resources.ConfirmationEmail.ToString().Replace("@Name", ticket.Name).Replace("@TicketDescription", ticket.Description).Replace("@TimeLogged", ticket.CreatedDate.ToString());

            msg.AddContent(MimeType.Html, emailBody);

            return(await client.SendEmailAsync(msg));
        }