简体   繁体   English

SendGrid在发送电子邮件时抛出InvalidApiRequestException

[英]SendGrid throwing InvalidApiRequestException in sending email

SendGrid is throwing an InvalidApiRequestException when sending an email. 发送电子邮件时,SendGrid引发InvalidApiRequestException

I am using this code: 我正在使用此代码:

public Task SendEmailAsync(string email, string subject, string message)
{
    // Plug in your email service here to send an email.
    var myMessage = new SendGrid.SendGridMessage();
    myMessage.AddTo(email);
    myMessage.From = new MailAddress("varshney@shobhit.com", "Shobhit", System.Text.Encoding.Default);
    myMessage.Subject = subject;
    myMessage.Text = message;
    myMessage.Html = message;
    var credentials = new NetworkCredential(
        Options.SendGridUser,
        Options.SendGridKey);
    // Create a Web transport for sending email.
    var transportWeb = new SendGrid.Web(credentials);
    // Send the email.
    if (transportWeb != null)
    {
        return transportWeb.DeliverAsync(myMessage);
    }
    else
    {
        return Task.FromResult(0);
    }
}

Stack Trace is: 堆栈跟踪为:

InvalidApiRequestException: Bad Request Check `Errors` for a list of errors returned by the API.
SendGrid.ErrorChecker.CheckForErrors(HttpResponseMessage response, Stream stream)
SendGrid.ErrorChecker.<CheckForErrorsAsync>d__1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
SendGrid.Web.<DeliverAsync>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
MessageBoard.Controllers.AccountController.<Register>d__9.MoveNext() in AccountController.cs
                    await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
Microsoft.AspNet.Mvc.Controllers.ControllerActionExecutor.<CastToObject>d__8`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
Microsoft.AspNet.Mvc.Controllers.ControllerActionInvoker.<InvokeActionAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
Microsoft.AspNet.Mvc.Controllers.FilterActionInvoker.<InvokeActionFilterAsync>d__53.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNet.Mvc.Controllers.FilterActionInvoker.<InvokeAsync>d__44.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNet.Mvc.Infrastructure.MvcRouteHandler.<RouteAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNet.Routing.Template.TemplateRoute.<RouteAsync>d__27.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNet.Routing.RouteCollection.<RouteAsync>d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNet.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNet.IISPlatformHandler.IISPlatformHandlerMiddleware.<Invoke>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNet.Diagnostics.Entity.MigrationsEndPointMiddleware.<Invoke>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNet.Diagnostics.Entity.DatabaseErrorPageMiddleware.<Invoke>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNet.Diagnostics.Entity.DatabaseErrorPageMiddleware.<Invoke>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNet.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>d__7.MoveNext()

Make sure you are using SendGrid C# Library version 6.3.x or later. 确保您使用的是SendGrid C#库6.3.x或更高版本。 There was a bug in the previous library version. 先前的库版本中存在一个错误。

For your credentials, are you using your Sendgrid username and password? 对于您的凭据,您是否使用您的Sendgrid用户名和密码? Or your API key? 还是您的API密钥? From your variable names it appears you are passing your API key. 从变量名看来,您正在传递API密钥。 Try passing your password instead: 尝试改为通过密码:

Options.SendGridUser Options.SendGridPassword Options.SendGridUser Options.SendGridPassword

I was facing same issue. 我面临着同样的问题。 In my case root cause was some German characters in email address. 就我而言,根本原因是电子邮件地址中有一些德语字符。 To log exact error try adding below try/catch block. 要记录确切的错误,请尝试在try / catch块下面添加。

            try
            {
                // Create a Web transport for sending email.
                var transportWeb = new SendGrid.Web(credentials);
                // Send the email.
                if (transportWeb != null)
                {
                    return transportWeb.DeliverAsync(myMessage);
                }
            }
            catch (InvalidApiRequestException exception)
            {
                if (exception.Errors != null)
                {
                    foreach (var error in exception.Errors)
                    {
                        // Log error
                    }
                } 
            }

Easy to consume the sendgrid API without any packages (Except newtonsoft json). 无需使用任何程序包即可轻松使用sendgrid API(newtonsoft json除外)。 In my sample, I use templates; 在我的示例中,我使用模板; You can use content with outcommenting the content field 您可以在内容字段中添加注释

1) Create your Classes 1)创建课程

public class MailObject
    {
        public ICollection<MailPersonalizations> personalizations { get; set; }
        public Email from { get; set; }
        public string template_id { get; set; }
        //public ICollection<MailContent> content { get; set; }
    }

public class MailPersonalizations
    {
        public ICollection<Email> to { get; set; }
        public string subject { get; set; }
        public Dictionary<string, string> substitutions { get; set; }
    }

public class MailContent
    {
        public string type { get; set; }
        public string value { get; set; }
    }

public class Email
    {
        public string email { get; set; }
        public string name { get; set; }
    }

2) Create your MailObject and send it with HttpClient 2)创建您的MailObject并使用HttpClient发送

public async Task SendEmailAsync(string email, string subject, string message, string url = "", string buttonText = "")
        {
            //Create a mail object
            var mailObject = new MailObject {
                personalizations = new List<MailPersonalizations>(),
                from = new Email { email = "no-reply@passion4it.be", name = "No-Reply Passion4IT" },
                template_id = "cc84680c-a569-428b-ab26-9618584bc9ae"
            };

            //create the mail personalization
            var personalization = new MailPersonalizations();
            personalization.to = new List<Email>();
            personalization.to.Add(new Email { email = email});
            personalization.subject = subject;
            //Substitutions
            personalization.substitutions = new Dictionary<string, string>();
            personalization.substitutions.Add("-url-", url);
            personalization.substitutions.Add("-title-", subject);
            personalization.substitutions.Add("-custtext-", message);
            personalization.substitutions.Add("-buttonText-", buttonText);

            mailObject.personalizations.Add(personalization); //Adding to the mail object

            //SEND EMAIL USING SENDGRID API
            using(var client = new HttpClient())
            {
                var jsonMail = JsonConvert.SerializeObject(mailObject);//convert object

                client.DefaultRequestHeaders.Accept.Clear(); //Clear headers
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //Add Accept type
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR API KEY"); //Add Authorization

                var response = await client.PostAsync("https://api.sendgrid.com/v3/mail/send", new StringContent(jsonMail, Encoding.UTF8, "application/json")); //Send the mail
            }

            return; //Closed
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM