public async Task<string> Send(IMessage message)
        {
            var msg = new SendGridMessage();

            msg.Subject = message.Subject;
            msg.From = new MailAddress(message.From);
            msg.Html = message.Body;

            msg.AddTo(message.To);

            msg.EnableClickTracking();
            msg.EnableOpenTracking();

            try
            {
                var transportWeb = new Web(_apiKey);
                await transportWeb.DeliverAsync(msg);
            }
            catch (Exception ex)
            {
                throw new MailerException(ex.Message, MailerException.enReason.RejectByProvider);
            }

            return null;
        }
        public override async Task<bool> SendNotificationAsync(PushNotificationItem notificationItem, object message, CancellationToken ct)
        {
            var cfg = (SendGridDeliveryProviderConfiguration)Configuration;
            var sent = false;
            //implicit conversion operator
            MailMessage smsg = message as SerializableMailMessage;
            if (smsg != null)
            {
                try
                {
                    var hView = smsg.AlternateViews.First(v => v.ContentType.MediaType == "text/html");
                    var tView = smsg.AlternateViews.First(v => v.ContentType.MediaType == "text/plain");
                    var sendGridMessage = new SendGridMessage
                    {
                        To = new[]
                        {
                            new MailAddress(notificationItem.Destination.DestinationAddress,
                                notificationItem.Destination.SubscriberName)
                        },
                        From = new MailAddress(cfg.FromAddress, cfg.FromDisplayName),
                        Subject = smsg.Subject,
                        Html = hView.ContentStream.ReadToString(),
                        Text = tView.ContentStream.ReadToString()
                    };

                    if (cfg.EnableClickTracking ?? false)
                    {
                        sendGridMessage.EnableClickTracking();
                    }
                    if (cfg.EnableGravatar ?? false)
                    {
                        sendGridMessage.EnableGravatar();
                    }
                    if (cfg.EnableOpenTracking ?? false)
                    {
                        sendGridMessage.EnableOpenTracking();
                    }
                    if (cfg.SendToSink ?? false)
                    {
                        sendGridMessage.SendToSink();
                    }

                    var transport = new Web(cfg.ApiKey);
                    await transport.DeliverAsync(sendGridMessage);
                    sent = true;
                }
                catch
                {
                    sent = false;
                    //TODO: log this somewhere
                }

            }
            return sent;
        }
        public void Send()
        {
            SendGridMessage client = new SendGridMessage();
            client.From = new MailAddress(From);
            client.AddTo(To);
            client.Subject = Subject;
            client.Text = Regex.Replace(Body, "<.*?>", string.Empty);
            client.Html = Body.Replace("\r\n", "<br>");
            client.EnableClickTracking();
            client.EnableOpenTracking();

            Web transport = new Web(ConfigurationManager.AppSettings[GetType().Name]);
            transport.DeliverAsync(client).ConfigureAwait(false);
        }
Esempio n. 4
0
        /// <summary>
        /// Sends the mail batch using the SendGrid API
        /// </summary>
        /// <param name="mail">The mail.</param>
        /// <param name="recipients">The recipients.</param>
        /// <param name="onlyTestDontSendMail">if set to <c>true</c> [only test dont send mail].</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public override bool SendMailBatch(MailInformation mail, IEnumerable<JobWorkItem> recipients, bool onlyTestDontSendMail)
        {
            var settings = GetSettings();

            if (recipients == null || recipients.Any() == false)
                throw new ArgumentException("No workitems", "recipients");

            if (recipients.Count() > 1000)
                throw new ArgumentOutOfRangeException("recipients", "SendGrid supports maximum 1000 recipients per batch send.");

            var msg = new SendGridMessage();
            msg.From = new MailAddress(mail.From);
            msg.Subject = mail.Subject;
            msg.Html = mail.BodyHtml;
            msg.Text = mail.BodyText;

            // Add recipinets to header, to hide other recipients in to field.
            List<string> addresses = recipients.Select(r => r.EmailAddress).ToList();
            msg.Header.SetTo(addresses);
            msg.AddSubstitution("%recipient%", addresses);
            // To send message we need to have a to address, set that to from
            msg.To = new MailAddress[] { msg.From };

            if (mail.EnableTracking)
            {
                // true indicates that links in plain text portions of the email
                // should also be overwritten for link tracking purposes.
                msg.EnableClickTracking(true);
                msg.EnableOpenTracking();
            }

            if(mail.CustomProperties.ContainsKey("SendGridCategory"))
            {
                string category = mail.CustomProperties["SendGridCategory"] as string;
                if (string.IsNullOrEmpty(category) == false)
                    msg.SetCategory(category);
            }

            var credentials = new NetworkCredential(settings.Username, settings.Password);

            // Create an Web transport for sending email.
            var transportWeb = new Web(credentials);

            transportWeb.Deliver(msg);

            return true;
        }
        public void Test_EnablingOpenTracking()
        {
            var mail = BasicMailBuilder
                .EnableOpenTracking()
                .Build();

            var message = new SendGridMessage();
            message.EnableOpenTracking();
            Assert.IsFalse(string.IsNullOrEmpty(message.Header.JsonString()));
            Assert.AreEqual(message.Header.JsonString(), mail.Header.JsonString());
        }
Esempio n. 6
0
        /// <summary>
        ///     Enable the Open Tracking to track when emails are opened.
        ///     http://docs.sendgrid.com/documentation/apps/open-tracking/
        /// </summary>
        public void EnableOpenTrackingEmail()
        {
            //create a new message object
            var message = new SendGridMessage();

            //set the message recipients
            foreach (var recipient in _to)
            {
                message.AddTo(recipient);
            }

            //set the sender
            message.From = new MailAddress(_from);

            //set the message body
            message.Html = "<p style='color:red';>Hello World Plain Text</p>";

            //set the message subject
            message.Subject = "Hello World Open Tracking Test";

            //create an instance of the Web transport mechanism
            var transportInstance = new Web(new NetworkCredential(_username, _password));

            //enable gravatar
            message.EnableOpenTracking();

            //send the mail
            transportInstance.DeliverAsync(message);
        }
        public static void SendEmailViaSendGrid(string to, string from, string subject, string htmlBody, MailType type, string textBody, string[] multipleTo = null)
        {
            try
            {
                //var message = SendGrid.GenerateInstance();
                var message = new SendGridMessage();
                if (String.IsNullOrEmpty(to))
                    message.AddTo(multipleTo);
                else
                    message.AddTo(to);

                //if (multipleTo != null)
                //    message.AddTo(multipleTo);
                //else
                //    message.AddTo(to);

                message.From = new System.Net.Mail.MailAddress(from);
                message.Subject = subject;
                if (type == MailType.TextOnly)
                    message.Text = textBody.Replace(@"\r\n", Environment.NewLine);
                else if (type == MailType.HtmlOnly)
                    message.Html = htmlBody;
                else
                {
                    message.Html = htmlBody;
                    message.Text = textBody;
                }

                //Dictionary<string, string> collection = new Dictionary<string, string>();
                //collection.Add("header", "header");
                //message.Headers = collection;

                message.EnableOpenTracking();
                message.EnableClickTracking();
                message.DisableUnsubscribe();
                message.DisableFooter();
                message.EnableBypassListManagement();
                //var transportInstance = SMTP.GenerateInstance(new System.Net.NetworkCredential(SendGridUsername, SendGridPassword), SendGridSmtpHost, SendGridSmtpPort);
                var transportInstance = new Web(new System.Net.NetworkCredential(SendGridUsername, SendGridPassword));
                transportInstance.Deliver(message);
                if (String.IsNullOrEmpty(to))
                    Console.WriteLine("SendGrid: Email was sent successfully to " + multipleTo);
                else
                    Console.WriteLine("SendGrid: Email was sent successfully to " + to);
            }
            catch (Exception)
            {
                if (String.IsNullOrEmpty(to))
                    Console.WriteLine("SendGrid: Unable to send email to " + multipleTo);
                else
                    Console.WriteLine("SendGrid: Unable to send email to " + to);
                throw;
            }
        }
Esempio n. 8
0
 public MailBuilder EnableOpenTracking()
 {
     sendgrid.EnableOpenTracking();
     return(this);
 }
        public void EnableOpenTracking()
        {
            var header = new Header();
            var sendgrid = new SendGridMessage(header);

            sendgrid.EnableOpenTracking();

            var json = header.JsonString();
            Assert.AreEqual("{\"filters\" : {\"opentrack\" : {\"settings\" : {\"enable\" : \"1\"}}}}", json);
        }