Bad Request error using SendGrid SMTP email submis

2019-05-08 03:58发布

问题:

I am currently using C# in MVC4 ASP.NET 4.5.

My application creates a user and then submits a registration email to that use to authenticate their email. To create this script, I followed this tutorial: How to Send Email Using SendGrid with Windows Azure

I am using the latest version of SendGrid (2.1.1)

Code specific namespaces being used:

using SendGridMail;
using System.Net;
using System.Net.Mail;

Here is my code that creates the SendGrid mail message:

SendGrid message = SendGrid.GetInstance();
message.From = new MailAddress(fromEmail); //fromEmail is a MailAddress type
message.AddTo(userName); //this is a string
message.Html = body; //this is also a string

Then I go to send the email:

//Create login info for email
NetworkCredential credentials = new NetworkCredential("username", "password");
var trasnportSMTP = Web.GetInstance(credentials);
trasnportSMTP.Deliver(message); //smtp.sendgrid.net Send message

On the last line where "trasnportSMTP.Deliver(message);" I get this error:

Server Error in '/' Application.

Bad Request

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Exception: Bad Request

The only things I've noticed while tracing is in the Exception Snapshot in View Details and the Output window.

I noticed that the: TargetSite = {Void CheckForErrors(System.Net.Http.HttpResponseMessage)}, ReturnType is {Name = "Void" FullName = "System.Void"}, ReflectedType is {Name = "Web" FullName = "SendGridMail.Web"}, CustomAttributes - Count = 0, Name = "CheckForErrors", It's in the Module {SendGridMail.dll}.

Also in my output, there is the following: "A first chance exception of type 'System.FormatException' occurred in System.dll Step into: Stepping over non-user code 'SendGridMail.Web.Deliver'"

Can anyone give me some more insight on why this error is happening. I am using the correct username and password that is on the SendGrid account on Azure.

Thank you ahead of time.

回答1:

Try adding the subject to your message

message.Subject = "this is the subject";

That should do it, I ran into the same problem when I was playing with this library.



回答2:

This answer helped me (I'm using Azure):

SendGrid Tutorial resulting in Bad Request

In short: you need to get your credentials through azure (connect info at the marketplace), you might be using the wrong ones.



回答3:

Digging through the documentation if you need to use the key which looks like something closer to "SG.asasfhiouce-JKIjjkvcdb_iouywerejkhwrnd" you should use the exact word "apikey" as the username and that key as the password

If it didn't work, try adding to the header "Authorization" with value "Bearer API_KEY_ABOVE_AS_WELL" so it looks like

"Authorization" "Bearer SG.asasfhiouce-JKIjjkvcdb_iouywerejkhwrnd"