【问题标题】:Converting SMTP Sendgrid to Sendgrid API将 SMTP Sendgrid 转换为 Sendgrid API
【发布时间】:2020-10-23 02:56:27
【问题描述】:

目前正在将旧的 SMTP Sendgrid 替换为 API Sendgrid,我注意到它们的代码存在一些差异。但我在想,因为它们都是 sendgrid,所以它可以正常工作。我所做的是在最后添加这个SendGridClient.SendEmailAsync(Message);。但它说

无法从 system.net.mail.mailmessage 转换为 sendgrid.helpers.mail.sendgridmessage

这是正确的转换方式吗?

下面是代码。

        try
        {
            string SendGridKey = ConfigurationManager.AppSettings["SendGridKey"];
            var SendGridClient = new SendGridClient(SendGridKey);
            using (MailMessage MessageContent = new MailMessage())
            {
                MessageContent.From = new MailAddress(From);
                MessageContent.To.Add(new MailAddress(To));
                MessageContent.Subject = Subject;
                MessageContent.Body = (TextBody);
                ContentType mimeType = new System.Net.Mime.ContentType("text/html");
                AlternateView Alternate = AlternateView.CreateAlternateViewFromString(HtmlBody, mimeType);
                Message.AlternateViews.Add(Alternate);
                if (AttachedFileName == true)
                {
                    Attachment AttachedFile = new Attachment(HttpRuntime.AppDomainAppPath + "Path\\" + AttachedFileName);
                    MessageContent.Attachments.Add(AttachedFile);
                }

                //using (SmtpClient Client = new SmtpClient())
                //{
                //    Client.EnableSsl = true;
                //    Client.Send(MessageContent);
                //}
                  SendGridClient.SendEmailAsync(Message);
            }
            return;
        }

【问题讨论】:

  • 你需要创建一个sendgrid.helpers.mail.sendgridmessage类的对象并设置它的属性,然后将它传递给SendGridClient.SendEmailAsyc方法。
  • 我已经这样做了。我能够成功发送电子邮件。但我希望只更改旧 smtp 中的几行代码,而不是创建一个全新的。
  • 在 github 上为此打开了一个问题 ...github.com/sendgrid/sendgrid-csharp/issues/266 可能您可以编写自己的实现并帮助社区..

标签: c# asp.net sendgrid


【解决方案1】:

要使用 SendGrid API 发送邮件,您需要创建 com.sendgrid.Request 对象。为java添加代码:

import com.sendgrid.Content;
import com.sendgrid.Email;
import com.sendgrid.Mail;
import com.sendgrid.Method;
import com.sendgrid.Request;
import com.sendgrid.SendGrid;

Email from = new Email("<FROM_EMAIL>");
String subject = "<SUBJECCT>";
Email to = new Email("<TO_EMAIL>");
Content content = new Content("text/plain", message);
Mail mail = new Mail(from, subject, to, content);
SendGrid sg = new SendGrid(SendGridKey);
Request request = new Request();
try {
    request.setMethod(Method.POST);
    request.setEndpoint("mail/send");
    request.setBody(mail.build());
    sg.api(request);
    log.info("Main sent successfully");
} catch (IOException ex) {
    log.info("Error while sending mail: {}", ex.toString());
}

【讨论】:

    猜你喜欢
    • 2012-09-02
    • 1970-01-01
    • 1970-01-01
    • 2013-06-13
    • 1970-01-01
    • 2011-09-05
    • 1970-01-01
    • 1970-01-01
    • 2018-03-10
    相关资源
    最近更新 更多