【问题标题】:How do I to use MailMessage to send mail using SendGrid?如何使用 MailMessage 使用 SendGrid 发送邮件?
【发布时间】:2020-04-30 14:28:44
【问题描述】:

我正在尝试使用 SendGrid 发送邮件,但我不能。它总是抛出一个我无法修复的异常。

我该如何解决这个问题?

发送邮件

public static Boolean isSend(IList<String> emailTo, String mensagem, String assunto, String emailFrom, String emailFromName){        
        try{            
            MailMessage mail = new MailMessage();
            mail.BodyEncoding = System.Text.Encoding.UTF8;
            mail.SubjectEncoding = System.Text.Encoding.UTF8;
            //to
            foreach (String e in emailTo) {
                mail.To.Add(e);
            }             
            mail.From = new MailAddress(emailFrom);
            mail.Subject = assunto;            
            mail.Body = mensagem;
            mail.IsBodyHtml = true;
            SmtpClient smtp = new SmtpClient();
            smtp.Host = CustomEmail.SENDGRID_SMTP_SERVER;
            smtp.Port = CustomEmail.SENDGRID_PORT_587;            
            smtp.Credentials = new System.Net.NetworkCredential(CustomEmail.SENDGRID_API_KEY_USERNAME, CustomEmail.SENDGRID_API_KEY_PASSWORD);
            smtp.UseDefaultCredentials = false;
            smtp.EnableSsl = false;
            smtp.Timeout = 20000;
            smtp.Send(mail);
            return true;
        }catch (SmtpException e){
            Debug.WriteLine(e.Message);
            return false;
        }        
    }

自定义邮件

//SendGrid Configs   
    public const String SENDGRID_SMTP_SERVER = "smtp.sendgrid.net";
    public const int SENDGRID_PORT_587 = 587;
    public const String SENDGRID_API_KEY_USERNAME = "apikey"; //myself
    public const String SENDGRID_API_KEY_PASSWORD = "SG.xx-xxxxxxxxxxxxxxxxxxxxxxxxx-E";

例外

Exception thrown: 'System.Net.Mail.SmtpException' in System.dll
Server Answer: Unauthenticated senders not allowed

【问题讨论】:

  • 您是否尝试过通过此凭据手动连接到服务器?此外,将您的方法重命名为 TrySend,因为您实际上是在做一些有状态的事情。
  • 我强烈建议您查看 SendGrid 的 C# 库,除非您绝对必须直接使用 SMTP。 sendgrid.com/docs/for-developers/sending-email/…

标签: c# asp.net-mvc sendgrid


【解决方案1】:

对于使用 SendGrid 发送电子邮件,有 v3 API。 NuGet 名称为 SendGrid,链接为 here

此库不适用于System.Net.Mail.MailMessage,它使用SendGrid.Helpers.Mail.SendGridMessage

此库使用 API 密钥进行授权。您可以在登录 SendGrid Web 应用程序时创建一个,然后导航到电子邮件 API -> 集成指南 -> Web API -> C#。

var client = new SendGridClient(apiKey);
var msg = MailHelper.CreateSingleTemplateEmail(from, new EmailAddress(to), templateId, dynamicTemplateData);

try
{
    var response = client.SendEmailAsync(msg).Result;
    if (response.StatusCode != HttpStatusCode.OK
        && response.StatusCode != HttpStatusCode.Accepted)
    {
        var errorMessage = response.Body.ReadAsStringAsync().Result;
        throw new Exception($"Failed to send mail to {to}, status code {response.StatusCode}, {errorMessage}");
    }
}
catch (WebException exc)
{
    throw new WebException(new StreamReader(exc.Response.GetResponseStream()).ReadToEnd(), exc);
}

【讨论】:

  • 其实问题是我没有验证 sendgrid.com 上的电子邮件,添加后效果很好。非常感谢。
【解决方案2】:

我认为您的问题源于未在构造函数中使用服务器实例化 SMTP 客户端。此外,您应该将 smtpclient 包装在 using 语句中,以便正确处理它,或者在完成后调用 dispose。

试试这个:

    public static Boolean isSend(IList<String> emailTo, String mensagem, String assunto, String emailFrom, String emailFromName)
    {
        try
        {
            MailMessage mail = new MailMessage();
            mail.BodyEncoding = System.Text.Encoding.UTF8;
            mail.SubjectEncoding = System.Text.Encoding.UTF8;
            //to
            foreach (String e in emailTo)
            {
                mail.To.Add(e);
            }
            mail.From = new MailAddress(emailFrom);
            mail.Subject = assunto;
            mail.Body = mensagem;
            mail.IsBodyHtml = true;
            using(SmtpClient smtp = new SmtpClient(CustomEmail.SENDGRID_SMTP_SERVER)){
                smtp.Port = CustomEmail.SENDGRID_PORT_587;
                smtp.Credentials = new System.Net.NetworkCredential(CustomEmail.SENDGRID_API_KEY_USERNAME, CustomEmail.SENDGRID_API_KEY_PASSWORD);
                smtp.UseDefaultCredentials = false;
                smtp.EnableSsl = false;
                smtp.Timeout = 20000;
                smtp.Send(mail)
            }
        }
        catch (SmtpException e)
        {
            Debug.WriteLine(e.Message);
            return false;
        }
    }

如果这不起作用,您可以尝试删除 smtp 客户端的端口、enablessl 和 usedefaultcredentials 参数。我一直使用 sendgrid,不使用这些选项。

【讨论】:

    【解决方案3】:

    为了更具体地回答您的原始问题和异常原因,SendGrid SMTP 服务器可能不是在寻找您帐户的用户名和密码,而是在寻找您的 API 密钥。该错误似乎表明您的身份验证不成功。

    https://sendgrid.com/docs/for-developers/sending-email/v3-csharp-code-example/

    与 SendGrids SMTP API 集成:

    • 创建至少具有“邮件”权限的 API 密钥。
    • 将电子邮件客户端或应用程序中的服务器主机设置为 smtp.sendgrid.net。
      • 此设置有时称为外部 SMTP 服务器或 SMTP 中继。
    • 将您的用户名设置为 apikey。
    • 将您的密码设置为第 1 步中生成的 API 密钥。
    • 将端口设置为 587。

    使用 SendGrid C# 库也将简化此过程:

    https://sendgrid.com/docs/for-developers/sending-email/v3-csharp-code-example/

    // using SendGrid's C# Library
    // https://github.com/sendgrid/sendgrid-csharp
    using SendGrid;
    using SendGrid.Helpers.Mail;
    using System;
    using System.Threading.Tasks;
    
    namespace Example
    {
        internal class Example
        {
            private static void Main()
            {
                Execute().Wait();
            }
    
            static async Task Execute()
            {
                var apiKey = Environment.GetEnvironmentVariable("NAME_OF_THE_ENVIRONMENT_VARIABLE_FOR_YOUR_SENDGRID_KEY");
                var client = new SendGridClient(apiKey);
                var from = new EmailAddress("test@example.com", "Example User");
                var subject = "Sending with SendGrid is Fun";
                var to = new EmailAddress("test@example.com", "Example User");
                var plainTextContent = "and easy to do anywhere, even with C#";
                var htmlContent = "<strong>and easy to do anywhere, even with C#</strong>";
                var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
                var response = await client.SendEmailAsync(msg);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-23
      • 2016-09-01
      • 2018-11-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多