Ejemplo n.º 1
0
        public static void SendEmail(string emailToken, string from, string template, string[] to, string[] cc, string title, ILogger log)
        {
            log.LogInformation($"Sending email from {from} with title: {title}");

            SendGrid.SendGridClient client = new SendGrid.SendGridClient(emailToken);

            SendGrid.Helpers.Mail.SendGridMessage message = new SendGrid.Helpers.Mail.SendGridMessage();
            message.SetFrom(from);

            foreach (string item in to)
            {
                if (!string.IsNullOrEmpty(item))
                {
                    message.AddTo(item);
                }
            }

            foreach (string item in cc)
            {
                if (!string.IsNullOrEmpty(item))
                {
                    message.AddCc(item);
                }
            }

            message.SetSubject($"GitHub Report: {title}");
            message.AddContent(MimeType.Html, template);

#if !DEBUG
            var emailResult = client.SendEmailAsync(message).GetAwaiter().GetResult();
#else
            File.WriteAllText("output.html", template);
#endif
        }
Ejemplo n.º 2
0
        public async Task <SendEmailResult> SendEmailAsync(string recipient, string subject, string htmlContent, string plainTextContent)
        {
            var from = new SendGrid.Helpers.Mail.EmailAddress("*****@*****.**", "The Chesed Project");

            var to      = new SendGrid.Helpers.Mail.EmailAddress(recipient);
            var message = SendGrid.Helpers.Mail.MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);

            message.SetTemplateId("f54eaab7-93e1-48c4-9fc0-706fadd1af38");
            var mailResult = await _sendGridClient.SendEmailAsync(message);

            SendEmailResult result = new SendEmailResult();

            if ((mailResult.StatusCode == System.Net.HttpStatusCode.OK) || (mailResult.StatusCode == System.Net.HttpStatusCode.Accepted))
            {
                result.Success = true;
            }
            else
            {
                var badMailResponse = mailResult.DeserializeResponseBody(mailResult.Body);
                result.Success = false;
                foreach (var error in badMailResponse["errors"])
                {
                    result.Errors.Add(new SendEmailResult.SendEmailError
                    {
                        Message = error.message,
                        Field   = error.field,
                        Help    = error.help
                    });
                }
            }
            return(result);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Sends the e-mail from the provided email. Does not clean up blob like SendMailFromBlobAsync, you should do this yourself.
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public async Task <bool> SendMailAsync(Email email)
        {
            if (string.IsNullOrEmpty(_sendGridMailerOptions.ApiKey))
            {
                throw new ApplicationException("SendGridAPIKey is empty");
            }

            string emailFrom     = email.From;
            string emailFromName = HttpUtility.HtmlDecode(email.FromName);
            string emailTo       = email.To;
            string subject       = email.Subject; // already encoded in apply placeholders
            string body          = email.Body;    // already encoded in apply placeholders
            string bccs          = email.Bccs;
            string templateName  = email.TemplateName;
            Guid?  customerGuid  = email.CustomerGUID;

            var client = new SG.SendGridClient(_sendGridMailerOptions.ApiKey);

            var message = SG.Helpers.Mail.MailHelper.CreateSingleEmail(
                new SG.Helpers.Mail.EmailAddress(emailFrom, emailFromName),
                new SG.Helpers.Mail.EmailAddress(emailTo),
                subject,
                string.Empty,
                body
                );

            if (!string.IsNullOrWhiteSpace(bccs))
            {
                foreach (var bcc in bccs.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
                {
                    message.AddBcc(new SG.Helpers.Mail.EmailAddress(bcc));
                }
            }

            // we are only interested in mail events from mails to customers. If we don't have a customer guid,
            // then we also do not need to send the message id
            if (customerGuid.HasValue)
            {
                message.CustomArgs = new System.Collections.Generic.Dictionary <string, string>();
                message.CustomArgs.Add("CustomerGUID", customerGuid.ToString());
                message.CustomArgs.Add("MessageGUID", email.ID.ToString());
            }

            var result = await client.SendEmailAsync(message).ConfigureAwait(false);

            if (result.StatusCode == System.Net.HttpStatusCode.Accepted)
            {
                return(true);
            }
            else
            {
                // reading response https://github.com/sendgrid/sendgrid-csharp/blob/master/USAGE.md#post-mailsend
                var returnBody = string.Empty;
                if (result.Body != null)
                {
                    returnBody = await result.Body.ReadAsStringAsync();
                }
                throw new ApplicationException($"Sendgrid returned status code {result.StatusCode}, for {returnBody} with headers {result.Headers?.ToString()}");
            }
        }
        public async Task <bool> Send()
        {
            try
            {
                var myMessage = new SendGridMessage();
                myMessage.AddTo(Email, Reciever);
                myMessage.From        = new EmailAddress("*****@*****.**", "BendroCorp");
                myMessage.Subject     = Subject;
                myMessage.HtmlContent = Message + outro;

                var      transportWeb = new SendGrid.SendGridClient(Environment.GetEnvironmentVariable("SENDGRID_API_KEY")); //
                Response resp         = await transportWeb.SendEmailAsync(myMessage);                                        //.Wait();

                if (resp.StatusCode == System.Net.HttpStatusCode.OK || resp.StatusCode == System.Net.HttpStatusCode.Created || resp.StatusCode == System.Net.HttpStatusCode.Accepted)
                {
                    return(true);
                }
                else
                {
                    throw new Exception("Error Occured: Email could not be sent! " + resp.Body);
                }
            }
            catch (Exception)
            {
                return(false);
            }
        }
        public async Task <Response> SendMessageAsync(SendGridMessage msg, CancellationToken cancellationToken = default(CancellationToken))
        {
            var response = await _client.SendEmailAsync(msg, cancellationToken);

            if ((int)response.StatusCode >= 300)
            {
                string body = await response.Body.ReadAsStringAsync();

                throw new InvalidOperationException(body);
            }

            return(response);
        }
Ejemplo n.º 6
0
        private Task configSendGridasync(IdentityMessage message)
        {
            var client = new SendGrid.SendGridClient(ConfigurationManager.AppSettings["SendGridKey"].ToString());

            var myMessage = new SendGridMessage();

            myMessage.AddTo(message.Destination);
            myMessage.From             = new EmailAddress("*****@*****.**", "Ferretería y Materíales JYR");
            myMessage.Subject          = message.Subject;
            myMessage.PlainTextContent = message.Body;
            myMessage.HtmlContent      = message.Body;

            myMessage.SetClickTracking(false, false);
            return(client.SendEmailAsync(myMessage));
        }
Ejemplo n.º 7
0
    public Task Execute(string apiKey, string subject, string message, string email)
    {
        var client = new SendGrid.SendGridClient(apiKey);
        var msg    = new SendGridMessage()
        {
            //THIS MUST MATCH A VERIFIED EMAIL ACCOUNT IN SENDGRID
            From             = new EmailAddress("*****@*****.**", Options.SendGridUser),
            Subject          = subject,
            PlainTextContent = message,
            HtmlContent      = message
        };

        msg.AddTo(new EmailAddress(email));
        // Disable click tracking.
        // See https://sendgrid.com/docs/User_Guide/Settings/tracking.html
        msg.SetClickTracking(true, true);
        return(client.SendEmailAsync(msg));
    }
Ejemplo n.º 8
0
        public override async Task SendAsync(MailMessage message)
        {
            var oclient = new SG.SendGridClient(SmtpServer.ApiKey);

            var sgMessage = new SG.Helpers.Mail.SendGridMessage()
            {
                From = new SG.Helpers.Mail.EmailAddress()
                {
                    Email = DefaultFromEmail
                },
                Subject     = message.Subject,
                HtmlContent = message.Body
            };

            foreach (var to in message.To)
            {
                sgMessage.AddTo(to.Address, to.DisplayName);
            }

            await oclient.SendEmailAsync(sgMessage);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Use SendMailAsync in an Azure Function that is triggered by a queue message. It expects an id to a blob.
        /// </summary>
        /// <param name="id">id of blob</param>
        public async Task <bool> SendMailFromBlobAsync(string id)
        {
            if (string.IsNullOrEmpty(_sendGridMailerOptions.ApiKey))
            {
                throw new ApplicationException("SendGridAPIKey is empty");
            }

            // get blob information
            var blob = await _blobPersister.GetBlobClientAsync(_sendGridMailerOptions.BlobContainer, id.ToString());

            // check if the blob exists
            if (await blob.ExistsAsync())
            {
                var text = await blob.DownloadContentAsync();

                var email = Newtonsoft.Json.JsonConvert.DeserializeObject <Email>(text.Value.Content.ToString());

                string emailFrom     = email.From;
                string emailFromName = HttpUtility.HtmlDecode(email.FromName);
                string emailTo       = email.To;
                string subject       = email.Subject;
                string body          = email.Body;
                string bccs          = email.Bccs;
                string templateName  = email.TemplateName;
                Guid?  customerGuid  = email.CustomerGUID;

                var client = new SG.SendGridClient(_sendGridMailerOptions.ApiKey);

                var message = SG.Helpers.Mail.MailHelper.CreateSingleEmail(
                    new SG.Helpers.Mail.EmailAddress(emailFrom, emailFromName),
                    new SG.Helpers.Mail.EmailAddress(emailTo),
                    subject,
                    string.Empty,
                    body
                    );

                if (!string.IsNullOrWhiteSpace(bccs))
                {
                    foreach (var bcc in bccs.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        message.AddBcc(new SG.Helpers.Mail.EmailAddress(bcc));
                    }
                }

                // we are only interested in mail events from mails to customers. If we don't have a customer guid,
                // then we also do not need to send the message id
                if (customerGuid.HasValue)
                {
                    message.CustomArgs = new System.Collections.Generic.Dictionary <string, string>();
                    message.CustomArgs.Add("CustomerGUID", customerGuid.ToString());
                    message.CustomArgs.Add("MessageGUID", id);
                }

                var result = await client.SendEmailAsync(message).ConfigureAwait(false);

                if (result.StatusCode == System.Net.HttpStatusCode.Accepted)
                {
                    // clean up the blob
                    await blob.DeleteAsync();

                    return(true);
                }
                else
                {
                    // reading response https://github.com/sendgrid/sendgrid-csharp/blob/master/USAGE.md#post-mailsend
                    var returnBody = string.Empty;
                    if (result.Body != null)
                    {
                        try
                        {
                            returnBody = await result.Body.ReadAsStringAsync();
                        }
                        catch (Exception)
                        {
                            // leave the returnBody empty
                        }
                    }

                    throw new ApplicationException($"Sendgrid returned status code {result.StatusCode}, for {returnBody} with headers {result.Headers?.ToString()}");
                }
            }
            else
            {
                // blob doesn't exist
                throw new ApplicationException($"Blob {id} not found");
            }
        }
        public override Task SendAsync(MailMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            var oclient = new SG.SendGridClient(SmtpServer.ApiKey);

            var sgMessage = new SG.Helpers.Mail.SendGridMessage();

            var from = new SG.Helpers.Mail.EmailAddress();

            sgMessage.Subject     = message.Subject;
            sgMessage.HtmlContent = message.Body;

            if (message.From != null)
            {
                sgMessage.From = new SG.Helpers.Mail.EmailAddress(message.From.Address, message.From.DisplayName);
            }
            else
            {
                sgMessage.From = new SG.Helpers.Mail.EmailAddress(DefaultFromEmail, DefaultFromName);
            }

            if (message.Attachments != null & message.Attachments.Count > 0)
            {
                foreach (var attachment in message.Attachments)
                {
                    using (var reader = new System.IO.StreamReader(attachment.ContentStream))
                    {
                        string contentDisposition = null;
                        string contentType        = null;

                        if (attachment.ContentDisposition != null)
                        {
                            contentDisposition = attachment.ContentDisposition.DispositionType;
                        }

                        if (attachment.ContentType != null)
                        {
                            contentType = attachment.ContentType.Name;
                        }

                        sgMessage.AddAttachment(attachment.Name, reader.ReadToEnd(), contentType, contentDisposition, attachment.ContentId);
                    }
                }
            }

            foreach (var to in message.To)
            {
                sgMessage.AddTo(to.Address, to.DisplayName);
            }

            foreach (var cc in message.CC)
            {
                sgMessage.AddCc(cc.Address, cc.DisplayName);
            }

            foreach (var bcc in message.Bcc)
            {
                sgMessage.AddBcc(bcc.Address, bcc.DisplayName);
            }

            return(oclient.SendEmailAsync(sgMessage));
        }