任何使用 Sendgrid 的解析 API 和 c# ASP.NET MVC 的人

发布于 2024-11-02 10:07:33 字数 1436 浏览 1 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

丶情人眼里出诗心の 2024-11-09 10:07:33

如果有人尝试在 ASP.NET MVC 中执行此操作,这里是我的代码片段,用于解析 Sendgrid API Webhook 调用。

    [HttpPost]
    [Transaction]
    [ValidateInput(false)]
    public ActionResult SendGrid(int attachments, string charsets, string from, string headers, string html, string subject, string envelope, string text, string to, string cc) {
        try {
            StringBuilder logText = new StringBuilder();
            logText.AppendLine("From: " + from);
            logText.AppendLine("Headers: " + headers);
            logText.AppendLine("Text: " + text);
            logText.AppendLine("Html: " + html);
            logText.AppendLine("To: " + to);
            logText.AppendLine("Cc: " + cc);
            logText.AppendLine("Subject: " + subject);
            logText.AppendLine("Attachments: " + attachments);

            //Envelope Json
            Envelope envelopeObject = null;
            if (!string.IsNullOrEmpty(envelope)) {
                envelopeObject = JsonConvert.DeserializeObject<Envelope>(envelope);
                if (envelopeObject != null) {
                    logText.AppendLine("Envelope: [from]: " + envelopeObject.From);
                    if (envelopeObject.To != null && envelopeObject.To.Length > 0)
                        foreach (var envelopeTo in envelopeObject.To)
                            logText.AppendLine("Envelope: [To]: " + envelopeTo);
                }
            }

            //Charsets Json
            CharsetRequest charsetsObject = null;
            if (!string.IsNullOrEmpty(charsets)) {
                charsetsObject = JsonConvert.DeserializeObject<CharsetRequest>(charsets);
                if (charsetsObject != null) {
                    logText.AppendLine("Charsets: [To]: " + charsetsObject.To);
                    logText.AppendLine("Charsets: [From]: " + charsetsObject.From);
                    logText.AppendLine("Charsets: [Text]: " + charsetsObject.Text);
                    logText.AppendLine("Charsets: [Subject]: " + charsetsObject.Subject);
                    logText.AppendLine("Charsets: [Html]: " + charsetsObject.Html);
                }
            }

            List<EmailAttachment> emailAttachments = new List<EmailAttachment>();
            if (attachments > 0) {
                for (int i = 0; i < attachments; i++) {
                    HttpPostedFileBase file = Request.Files[i];
                    if (file.ContentLength > 0) {
                        var attachement = new EmailAttachment();
                        attachement.ContentLength = file.ContentLength;
                        attachement.ContentType = file.ContentType;
                        attachement.Filename = file.FileName;
                        attachement.CreateBy = 1;
                        attachement.CreateDate = DateTime.Now.ToUniversalTime();
                        logText.AppendLine("File: [FileName]: " + file.FileName);
                        logText.AppendLine("File: [ContentType]: " + file.ContentType);
                        logText.AppendLine("File: [FileSize]: " + file.ContentLength);
                        byte[] fileImage = new byte[attachement.ContentLength];
                        file.InputStream.Read(fileImage, 0, attachement.ContentLength);
                        attachement.FileContent = fileImage;
                        emailAttachments.Add(attachement);
                    }
                }
            }

            List<MailAddress> toEmailAddress = new List<MailAddress>();
            MailAddress dropboxEmail = null;

            //Parsing Headers
            Regex toline = new Regex(@"(?im-:^To\s*:\s*(?<to>.*)$)");
            Regex ccline = new Regex(@"(?im-:^Cc\s*:\s*(?<to>.*)$)");

            MailAddress senderEmail = new MailAddress(from);

            if (!string.IsNullOrEmpty(to))
                toEmailAddress.Add(new MailAddress(to));

            if (!string.IsNullOrEmpty(cc))
                toEmailAddress.Add(new MailAddress(cc));

            //Envelope Json
            if (!string.IsNullOrEmpty(envelope)) {
                envelopeObject = JsonConvert.DeserializeObject<Envelope>(envelope);
                if (envelopeObject != null) {
                    if (envelopeObject.To != null && envelopeObject.To.Length > 0)
                        foreach (var envelopeTo in envelopeObject.To) {
                            MailAddress mailTmp = new MailAddress(envelopeTo.Trim().ToLower());
                            if (mailTmp.User.Trim().StartsWith("dropbox", StringComparison.InvariantCultureIgnoreCase))
                                dropboxEmail = mailTmp;
                            else
                                toEmailAddress.Add(mailTmp);
                        }
                }
            }

            foreach (var email in ParseMIMEEmailAddresses(toline.Match(headers).Groups["to"].Value)) {
                MailAddress mailTmp = new MailAddress(email.Trim().ToLower());
                if (mailTmp.User.Trim().StartsWith("dropbox", StringComparison.InvariantCultureIgnoreCase))
                    dropboxEmail = mailTmp;
                else
                    toEmailAddress.Add(mailTmp);
            }

            foreach (var email in ParseMIMEEmailAddresses(ccline.Match(headers).Groups["to"].Value)) {
                MailAddress mailTmp = new MailAddress(email.Trim().ToLower());
                if (mailTmp.User.Trim().StartsWith("dropbox", StringComparison.InvariantCultureIgnoreCase))
                    dropboxEmail = mailTmp;
                else
                    toEmailAddress.Add(mailTmp);
            }

            foreach (var message in toEmailAddress)
                logText.AppendLine("HEADER PARSE [To]: " + message.Address);

            if (dropboxEmail != null)
                logText.AppendLine("Dropbox Email: " + dropboxEmail.Address);

            var dropLog = new DropboxLog {
                CreateDate = DateTime.Now.ToUniversalTime(),
                Log = logText.ToString()
            };
            _dropboxLogRepository.SaveOrUpdate(dropLog);
            _dropboxLogRepository.DbContext.CommitChanges();

            if (dropboxEmail == null)
                return new HttpStatusCodeResult(500);

            if (toEmailAddress.Count == 0)
                return new HttpStatusCodeResult(500);

            //Validate the the email came from a valid user/dropbox key.
            //TODO Also validate alias here
            var dropBoxKey = dropboxEmail.User.Split('+')[1];
            if (string.IsNullOrEmpty(dropBoxKey))
                return new HttpStatusCodeResult(500);
            var user = _userService.GetUserByEmailDropBoxId(senderEmail.Address, dropBoxKey);
            if (user == null)
                return new HttpStatusCodeResult(500);

            //Create email object
            var emailToAdd = new Email {
                CreateBy = user.Id,
                CreateDate = DateTime.Now.ToUniversalTime(),
                BodyText = text,
                BodyHtml = html,
                Subject = subject,
                Sender = user,
                EmailDate = DateTime.Now.ToUniversalTime(),
                Client = user.Client
            };

            foreach (var file in emailAttachments) {
                file.CreateBy = user.Id;
                emailToAdd.AddAttachment(file);
            }

            //Get all leads by email address list
            List<string> toEmails = toEmailAddress.Select(s => s.Address).ToList();
            foreach (Lead lead in _leadService.GetLeadsByEmails(user.Client.Id, user.Id, toEmails))
                lead.AddEmail(emailToAdd);

            foreach (Contact contact in _contactService.GetContactsByEmails(user.Client.Id, user.Id, toEmails))
                contact.AddEmail(emailToAdd);

            return new HttpStatusCodeResult(200);
        }
        catch (Exception ex) {
            var dropLog = new DropboxLog {
                CreateDate = DateTime.Now.ToUniversalTime(),
                Log = ex.Message
            };
            _dropboxLogRepository.SaveOrUpdate(dropLog);
            _dropboxLogRepository.DbContext.CommitChanges();
            throw;
        }
    }

    private static IEnumerable<string> ParseMIMEEmailAddresses(string lineToParse) {
        List<string> emails = new List<string>();

        int from = 0;
        int position = 0;
        string emailText;

        while (from < lineToParse.Length) {
            int found = (found = lineToParse.IndexOf(',', from)) > 0 ? found : lineToParse.Length;
            from = found + 1;
            emailText = lineToParse.Substring(position, found - position);

            try {
                MailAddress addy = new MailAddress(emailText.Trim());
                emails.Add(addy.Address);
                position = found + 1;
            }
            catch (FormatException) {
                //Log parsing error to database for future consideration.

            }
        }

        return emails;
    }

public class SendGridRequest
{
    public string Envelope { get; set; }
    public string Charsets { get; set; }
    public string SPF { get; set; }
    public int Attachments { get; set; }
    public string DKIM { get; set; }
    public string Headers { get; set; }
    public string From { get; set; }
    public string Html { get; set; }
    public string Subject { get; set; }
    public string Text { get; set; }
    public string To { get; set; }
    public string CC { get; set; }
}

public class Envelope
{
    public string From { get; set; }
    public string[] To { get; set; }
}

public class CharsetRequest
{
    public string From { get; set; }
    public string Html { get; set; }
    public string Subject { get; set; }
    public string Text { get; set; }
    public string To { get; set; }
    public string Cc { get; set; }
}

In case anyone is trying to do this in ASP.NET MVC, here is my code snipped to parse Sendgrid API Webhook call.

    [HttpPost]
    [Transaction]
    [ValidateInput(false)]
    public ActionResult SendGrid(int attachments, string charsets, string from, string headers, string html, string subject, string envelope, string text, string to, string cc) {
        try {
            StringBuilder logText = new StringBuilder();
            logText.AppendLine("From: " + from);
            logText.AppendLine("Headers: " + headers);
            logText.AppendLine("Text: " + text);
            logText.AppendLine("Html: " + html);
            logText.AppendLine("To: " + to);
            logText.AppendLine("Cc: " + cc);
            logText.AppendLine("Subject: " + subject);
            logText.AppendLine("Attachments: " + attachments);

            //Envelope Json
            Envelope envelopeObject = null;
            if (!string.IsNullOrEmpty(envelope)) {
                envelopeObject = JsonConvert.DeserializeObject<Envelope>(envelope);
                if (envelopeObject != null) {
                    logText.AppendLine("Envelope: [from]: " + envelopeObject.From);
                    if (envelopeObject.To != null && envelopeObject.To.Length > 0)
                        foreach (var envelopeTo in envelopeObject.To)
                            logText.AppendLine("Envelope: [To]: " + envelopeTo);
                }
            }

            //Charsets Json
            CharsetRequest charsetsObject = null;
            if (!string.IsNullOrEmpty(charsets)) {
                charsetsObject = JsonConvert.DeserializeObject<CharsetRequest>(charsets);
                if (charsetsObject != null) {
                    logText.AppendLine("Charsets: [To]: " + charsetsObject.To);
                    logText.AppendLine("Charsets: [From]: " + charsetsObject.From);
                    logText.AppendLine("Charsets: [Text]: " + charsetsObject.Text);
                    logText.AppendLine("Charsets: [Subject]: " + charsetsObject.Subject);
                    logText.AppendLine("Charsets: [Html]: " + charsetsObject.Html);
                }
            }

            List<EmailAttachment> emailAttachments = new List<EmailAttachment>();
            if (attachments > 0) {
                for (int i = 0; i < attachments; i++) {
                    HttpPostedFileBase file = Request.Files[i];
                    if (file.ContentLength > 0) {
                        var attachement = new EmailAttachment();
                        attachement.ContentLength = file.ContentLength;
                        attachement.ContentType = file.ContentType;
                        attachement.Filename = file.FileName;
                        attachement.CreateBy = 1;
                        attachement.CreateDate = DateTime.Now.ToUniversalTime();
                        logText.AppendLine("File: [FileName]: " + file.FileName);
                        logText.AppendLine("File: [ContentType]: " + file.ContentType);
                        logText.AppendLine("File: [FileSize]: " + file.ContentLength);
                        byte[] fileImage = new byte[attachement.ContentLength];
                        file.InputStream.Read(fileImage, 0, attachement.ContentLength);
                        attachement.FileContent = fileImage;
                        emailAttachments.Add(attachement);
                    }
                }
            }

            List<MailAddress> toEmailAddress = new List<MailAddress>();
            MailAddress dropboxEmail = null;

            //Parsing Headers
            Regex toline = new Regex(@"(?im-:^To\s*:\s*(?<to>.*)$)");
            Regex ccline = new Regex(@"(?im-:^Cc\s*:\s*(?<to>.*)$)");

            MailAddress senderEmail = new MailAddress(from);

            if (!string.IsNullOrEmpty(to))
                toEmailAddress.Add(new MailAddress(to));

            if (!string.IsNullOrEmpty(cc))
                toEmailAddress.Add(new MailAddress(cc));

            //Envelope Json
            if (!string.IsNullOrEmpty(envelope)) {
                envelopeObject = JsonConvert.DeserializeObject<Envelope>(envelope);
                if (envelopeObject != null) {
                    if (envelopeObject.To != null && envelopeObject.To.Length > 0)
                        foreach (var envelopeTo in envelopeObject.To) {
                            MailAddress mailTmp = new MailAddress(envelopeTo.Trim().ToLower());
                            if (mailTmp.User.Trim().StartsWith("dropbox", StringComparison.InvariantCultureIgnoreCase))
                                dropboxEmail = mailTmp;
                            else
                                toEmailAddress.Add(mailTmp);
                        }
                }
            }

            foreach (var email in ParseMIMEEmailAddresses(toline.Match(headers).Groups["to"].Value)) {
                MailAddress mailTmp = new MailAddress(email.Trim().ToLower());
                if (mailTmp.User.Trim().StartsWith("dropbox", StringComparison.InvariantCultureIgnoreCase))
                    dropboxEmail = mailTmp;
                else
                    toEmailAddress.Add(mailTmp);
            }

            foreach (var email in ParseMIMEEmailAddresses(ccline.Match(headers).Groups["to"].Value)) {
                MailAddress mailTmp = new MailAddress(email.Trim().ToLower());
                if (mailTmp.User.Trim().StartsWith("dropbox", StringComparison.InvariantCultureIgnoreCase))
                    dropboxEmail = mailTmp;
                else
                    toEmailAddress.Add(mailTmp);
            }

            foreach (var message in toEmailAddress)
                logText.AppendLine("HEADER PARSE [To]: " + message.Address);

            if (dropboxEmail != null)
                logText.AppendLine("Dropbox Email: " + dropboxEmail.Address);

            var dropLog = new DropboxLog {
                CreateDate = DateTime.Now.ToUniversalTime(),
                Log = logText.ToString()
            };
            _dropboxLogRepository.SaveOrUpdate(dropLog);
            _dropboxLogRepository.DbContext.CommitChanges();

            if (dropboxEmail == null)
                return new HttpStatusCodeResult(500);

            if (toEmailAddress.Count == 0)
                return new HttpStatusCodeResult(500);

            //Validate the the email came from a valid user/dropbox key.
            //TODO Also validate alias here
            var dropBoxKey = dropboxEmail.User.Split('+')[1];
            if (string.IsNullOrEmpty(dropBoxKey))
                return new HttpStatusCodeResult(500);
            var user = _userService.GetUserByEmailDropBoxId(senderEmail.Address, dropBoxKey);
            if (user == null)
                return new HttpStatusCodeResult(500);

            //Create email object
            var emailToAdd = new Email {
                CreateBy = user.Id,
                CreateDate = DateTime.Now.ToUniversalTime(),
                BodyText = text,
                BodyHtml = html,
                Subject = subject,
                Sender = user,
                EmailDate = DateTime.Now.ToUniversalTime(),
                Client = user.Client
            };

            foreach (var file in emailAttachments) {
                file.CreateBy = user.Id;
                emailToAdd.AddAttachment(file);
            }

            //Get all leads by email address list
            List<string> toEmails = toEmailAddress.Select(s => s.Address).ToList();
            foreach (Lead lead in _leadService.GetLeadsByEmails(user.Client.Id, user.Id, toEmails))
                lead.AddEmail(emailToAdd);

            foreach (Contact contact in _contactService.GetContactsByEmails(user.Client.Id, user.Id, toEmails))
                contact.AddEmail(emailToAdd);

            return new HttpStatusCodeResult(200);
        }
        catch (Exception ex) {
            var dropLog = new DropboxLog {
                CreateDate = DateTime.Now.ToUniversalTime(),
                Log = ex.Message
            };
            _dropboxLogRepository.SaveOrUpdate(dropLog);
            _dropboxLogRepository.DbContext.CommitChanges();
            throw;
        }
    }

    private static IEnumerable<string> ParseMIMEEmailAddresses(string lineToParse) {
        List<string> emails = new List<string>();

        int from = 0;
        int position = 0;
        string emailText;

        while (from < lineToParse.Length) {
            int found = (found = lineToParse.IndexOf(',', from)) > 0 ? found : lineToParse.Length;
            from = found + 1;
            emailText = lineToParse.Substring(position, found - position);

            try {
                MailAddress addy = new MailAddress(emailText.Trim());
                emails.Add(addy.Address);
                position = found + 1;
            }
            catch (FormatException) {
                //Log parsing error to database for future consideration.

            }
        }

        return emails;
    }

public class SendGridRequest
{
    public string Envelope { get; set; }
    public string Charsets { get; set; }
    public string SPF { get; set; }
    public int Attachments { get; set; }
    public string DKIM { get; set; }
    public string Headers { get; set; }
    public string From { get; set; }
    public string Html { get; set; }
    public string Subject { get; set; }
    public string Text { get; set; }
    public string To { get; set; }
    public string CC { get; set; }
}

public class Envelope
{
    public string From { get; set; }
    public string[] To { get; set; }
}

public class CharsetRequest
{
    public string From { get; set; }
    public string Html { get; set; }
    public string Subject { get; set; }
    public string Text { get; set; }
    public string To { get; set; }
    public string Cc { get; set; }
}
骄兵必败 2024-11-09 10:07:33

我认为你可以使用 RAZOR 解析器 example 来解析数据通过模板进行一些修改。

I think you can use RAZOR parser example to parse the data through templates with some modification.

独孤求败 2024-11-09 10:07:33

是的,我将它用于 www.totxt.com 和另一个网站,sendgrid 是一个很好的解决方案,比 POP3 好得多轮询,通常从您发送到发布到您的网站几乎是即时的。 〜亚历克斯

Yes, I use it for www.totxt.com and one other site, sendgrid is great solution, much better than POP3 polling, and generally almost instant from the time you send until it is posted to your site. ~alex

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文