示例#1
0
 public MailBuilder AddHeader(string key, string value)
 {
     sendgrid.AddHeaders(new Dictionary <string, string> {
         { key, value }
     });
     return(this);
 }
        public void CreateMimeMessage()
        {
            var message = new SendGridMessage();
            var attachment = Path.GetTempFileName();
            var text = "this is a test";
            var html = "<b>This<\b> is a better test";
            var headers = new KeyValuePair<String, String>("custom", "header");
            message.AddAttachment(attachment);
            message.Text = text;
            message.Html = html;
            message.AddTo("*****@*****.**");
            message.From = new MailAddress("*****@*****.**");
            message.AddHeaders(new Dictionary<string, string> {{headers.Key, headers.Value}});
            message.EnableGravatar();

            var mime = message.CreateMimeMessage();

            var sr = new StreamReader(mime.AlternateViews[0].ContentStream);
            var result = sr.ReadToEnd();
            Assert.AreEqual(text, result);

            sr = new StreamReader(mime.AlternateViews[1].ContentStream);
            result = sr.ReadToEnd();
            Assert.AreEqual(html, result);

            result = mime.Headers.Get(headers.Key);
            Assert.AreEqual(headers.Value, result);

            result = mime.Headers.Get("X-Smtpapi");
            var expected = "{\"filters\" : {\"gravatar\" : {\"settings\" : {\"enable\" : \"1\"}}}}";
            Assert.AreEqual(expected, result);

            result = mime.Attachments[0].Name;
            Assert.AreEqual(Path.GetFileName(attachment), result);
        }
示例#3
0
        public void TestFetchFormParamsHelper(Web webApi, bool credentials)
        {
            // Test Variables
            const string toAddress = "*****@*****.**";
            const string ccAddress = "*****@*****.**";
            const string bcc1Address = "*****@*****.**";
            const string bcc2Address = "*****@*****.**";
            MailAddress[] bccAddresses = {new MailAddress(bcc1Address), new MailAddress(bcc2Address)};
            const string fromAddress = "*****@*****.**";
            const string subject = "Test Subject";
            const string textBody = "Test Text Body";
            const string htmlBody = "<p>Test HTML Body</p>";
            const string headerKey = "headerkey";
            var testHeader = new Dictionary<string, string> { { headerKey, "headervalue" } };
            const string categoryName = "Example Category";

            var message = new SendGridMessage();
            message.AddTo(toAddress);
            message.AddCc(ccAddress);
            message.Bcc = bccAddresses;
            message.From = new MailAddress(fromAddress);
            message.Subject = subject;
            message.Text = textBody;
            message.Html = htmlBody;
            message.AddHeaders(testHeader);
            message.Header.SetCategory(categoryName);

            var result = webApi.FetchFormParams(message);
            if (credentials)
            {
                Assert.True(result.Any(r => r.Key == "api_user" && r.Value == TestUsername));
                Assert.True(result.Any(r => r.Key == "api_key" && r.Value == TestPassword));
            }
            Assert.True(result.Any(r => r.Key == "to[]" && r.Value == toAddress));
            Assert.True(result.Any(r => r.Key == "cc[]" && r.Value == ccAddress));
            Assert.True(result.Any(r => r.Key == "bcc[]" && r.Value == bcc1Address));
            Assert.True(result.Any(r => r.Key == "bcc[]" && r.Value == bcc2Address));
            Assert.True(result.Any(r => r.Key == "from" && r.Value == fromAddress));
            Assert.True(result.Any(r => r.Key == "subject" && r.Value == subject));
            Assert.True(result.Any(r => r.Key == "text" && r.Value == textBody));
            Assert.True(result.Any(r => r.Key == "html" && r.Value == htmlBody));
            Assert.True(
                result.Any(
                    r => r.Key == "headers" && r.Value == String.Format("{{\"{0}\":\"{1}\"}}", headerKey, testHeader[headerKey])));
            Assert.True(
                result.Any(r => r.Key == "x-smtpapi" && r.Value == String.Format("{{\"category\" : \"{0}\"}}", categoryName)));
        }
示例#4
0
        //Note that at the moment, we actually are submitting through SendGrid, not Gmail.
        public async void Send(EnvelopeDO envelope)
        {
            if (envelope == null)
                throw new ArgumentNullException("envelope");
            if (!string.Equals(envelope.Handler, EnvelopeDO.SendGridHander, StringComparison.OrdinalIgnoreCase))
                throw new ArgumentException(@"This envelope should not be handled with Gmail.", "envelope");
            if (envelope.Email == null)
                throw new ArgumentException(@"This envelope has no Email.", "envelope");
            if (envelope.Email.Recipients.Count == 0)
                throw new ArgumentException(@"This envelope has no recipients.", "envelope");
            
            var email = envelope.Email;
            if (email == null)
                throw new ArgumentException(@"Envelope email is null", "envelope");

            try
            {
                var fromName = !String.IsNullOrWhiteSpace(email.FromName) ? email.FromName : email.From.Name;

                var mailMessage = new SendGridMessage { From = new MailAddress(email.From.Address, fromName) };

                if (!String.IsNullOrWhiteSpace(email.ReplyToAddress))
                {
                    mailMessage.ReplyTo = new[] { new MailAddress(email.ReplyToAddress, email.ReplyToName) };
                }

                mailMessage.To = email.To.Select(toEmail => new MailAddress(toEmail.Address, toEmail.NameOrAddress())).ToArray();
                mailMessage.Bcc = email.BCC.Select(bcc => new MailAddress(bcc.Address, bcc.NameOrAddress())).ToArray();
                mailMessage.Cc = email.CC.Select(cc => new MailAddress(cc.Address, cc.NameOrAddress())).ToArray();

                mailMessage.Subject = email.Subject;

                if ((email.PlainText == null || email.HTMLText == null) && string.IsNullOrEmpty(envelope.TemplateName))
                {
                    throw new ArgumentException("Trying to send an email that doesn't have both an HTML and plain text body");
                }

                if (email.PlainText == null || email.HTMLText == null)
                {
                    mailMessage.Html = "<html></html>";
                    mailMessage.Text = "";
                }
                else
                {
                    mailMessage.Html = email.HTMLText;
                    mailMessage.Text = email.PlainText;
                }

                var headers = new Dictionary<String, String>();
                if (!String.IsNullOrEmpty(email.MessageID))
                    headers.Add("Message-ID", email.MessageID);
                if (!String.IsNullOrEmpty(email.References))
                    headers.Add("References", email.References);

                if (headers.Any())
                    mailMessage.AddHeaders(headers);

                foreach (var attachment in email.Attachments)
                {
                    mailMessage.AddAttachment(attachment.GetData(), attachment.OriginalName);
                }

                if (!string.IsNullOrEmpty(envelope.TemplateName))
                {
                    mailMessage.EnableTemplateEngine(envelope.TemplateName);//Now TemplateName will be TemplateId on Sendgrid.
                    if (envelope.MergeData != null)
                    {
                        //Now, we need to do some magic.
                        //Basically - we need the length of each substitution to match the length of recipients
                        //In our case, most of the time, all the substitutions are the same, except for token-related fields
                        //To make it easier to use, we attempt to pad out the substition arrays if they lengths don't match
                        //We only do that if we're given a string value. In any other case, we allow sengrid to fail.
                        var subs = new Dictionary<String, List<String>>();
                        foreach (var pair in envelope.MergeData)
                        {

                            var arrayType = pair.Value as JArray;
                            List<String> listVal;
                            if (arrayType != null)
                            {
                                listVal = arrayType.Select(a => a.ToString()).ToList();
                            }
                            else
                            {
                                listVal = new List<string>();
                                for (var i = 0; i < email.Recipients.Count(); i++) //Pad out the substitution
                                    listVal.Add(pair.Value == null ? String.Empty : pair.Value.ToString());
                            }
                            subs.Add(pair.Key, listVal);
                            
                        }
                        foreach(var sub in subs)
                            mailMessage.AddSubstitution(sub.Key, sub.Value);
                    }
                }

                try
                {
                    await _transport.DeliverAsync(mailMessage);

                    OnEmailSent(email.Id);
                }
                catch (Exception ex)
                {
                    OnEmailRejected(ex.Message, email.Id);
                }
            }
            catch (Exception ex)
            {
                OnEmailCriticalError(-1, "Unhandled exception.", ex.Message, email.Id);
            }
        }