Esempio 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
        }
Esempio n. 2
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);
            }
        }
Esempio n. 4
0
 public ShippingController(SignInManager <ApplicationUser> signInManager,
                           SendGrid.SendGridClient sendGridClient,
                           Braintree.BraintreeGateway braintreeGateway,
                           AmonTestContext context)
 {
     this._signInManager  = signInManager;
     this._sendGridClient = sendGridClient;
     _braintreeGateway    = braintreeGateway;
     _context             = context;
 }
Esempio n. 5
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));
        }
Esempio n. 6
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));
    }
Esempio n. 7
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);
        }
        async static Task RunAsync()
        {
            var email          = "*****@*****.**";
            var sendGridApiKey = ConfigurationManager.AppSettings["SendGridApiKey"];

            var    client      = new SendGrid.SendGridClient(sendGridApiKey);
            string queryParams = $"{{'limit':100,'email': '{email}'}}";
            var    response    = await client.RequestAsync(method : SendGridClient.Method.GET, urlPath : "email_activity", queryParams : queryParams);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var json = await response.Body.ReadAsStringAsync();

                if (!string.IsNullOrEmpty(json))
                {
                    var emailActivity = JsonConvert.DeserializeObject <List <SendGridQueryResponseModel> >(json);
                    if (emailActivity.FirstOrDefault(x => x.@event == "open") != null)
                    {
                        var emailConfirmed = true;
                    }
                }
            }
        }
Esempio n. 9
0
 public LoginController(SignInManager <Models.ApplicationUser> signInManager, SendGrid.SendGridClient sendGridClient)
 {
     this._signInManager  = signInManager;
     this._sendGridClient = sendGridClient;
 }
 public SendGridClient(string apiKey)
 {
     _client = new SendGrid.SendGridClient(apiKey);
 }
Esempio n. 11
0
 public AccountController(SignInManager <ApplicationUser> signInManager, SendGrid.SendGridClient sendGridClient)
 {
     this._signInManager  = signInManager;
     this._sendGridClient = sendGridClient;
 }
Esempio n. 12
0
 public EmailService(string apiKey)
 {
     this._sendGridClient = new SendGrid.SendGridClient(apiKey);
 }
Esempio n. 13
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));
        }
Esempio n. 15
0
 public ContactController(SendGrid.SendGridClient sendGridClient)
 {
     this._sendGridClient = sendGridClient;
 }