Bad Request error using SendGrid SMTP email submission - c#

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.

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.

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.

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"

Related

Counting Emails in inbox from SSIS (C#) - The remote server returned an error: (401) Unauthorized

I am trying to create a connection to the ExchangeService from a script component (C#) in SSIS to be able to count the total number of emails in an inbox.
My error comes when I try to use the connection - so far I've been testing the connection to simply try and send a test email to myself and its on msg.send() that I get the error:
The remote server returned an error: (401) Unauthorized
I have been using the WebServices (EWS) NuGet Package with the code below:
ExchangeService exService = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
string username = "emailUser";
string pwd = "MyPwd";
string domain = "NetBIOS_DOMAIN";
exService.Credentials = new WebCredentials(username, pwd, domain);
exService.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
EmailMessage msg = new EmailMessage(exService)
{
Subject = "This is a test!!!",
Body = "This is the message body"
};
msg.ToRecipients.Add("emailUser#domain.co.uk");
msg.Send();
I've not got as far as looking into inboxes yet because as soon as I try to bind a folder I get the same error so figured this was an easier test.
I have tried both WebCredentials() and NetworkCredential() - both give the same error.
I have been primarily following the notes from here
A search on the error led me to try all manor of variances with the username/domain as outlined in an answer here
And I have tested my remote connectivity with this tool which gives the same error (Screenshot)
I am testing this with my own credentials at present but eventually it would be replaced with a different used or a service account. I think everything is pointing at me entering them wrong somehow but I'm 2 days in and totally stumped.
Thanks all

Error in EmailMessage.Forward (EWS) method.

I'm using EWS to read a mailbox and based on a certain conditions, forward the emails out to a set of users. However, the process fails with this error:
"An internal server error occurred. The operation failed."
and this:
"An unhandled exception of type 'Microsoft.Exchange.WebServices.Data.ServiceResponseException' occurred in Microsoft.Exchange.WebServices.dll"
Here's my sample code:
EmailAddress[] emailids = new EmailAddress[4];
emailids[0] = new EmailAddress("user1#domain.com");
emailids[1] = new EmailAddress("user2#domain.com");
msg.Forward("This message was Auto forwarded", emailids);
The msg is an object of type EmailMessage in Microsoft.Exchange.WebServices.Data;
Any help would be appreciated.
Thank you
Abhi
In your code you've defined an array of 4 EmailAddress but you are only using 2 which would cause issues.
Does this fail on every message you try to forward or just certain messages or are you forwarding as batch and fails after a certain number.
There are Throttling restrictions with Exchange http://msdn.microsoft.com/en-us/library/office/jj945066(v=exchg.150).aspx that can affect a number of things one of those in the recipient limits eg RecipientRateLimit and ForwardeeLimit.
You might also want to enable tracing http://msdn.microsoft.com/en-us/library/office/dd633676(v=exchg.80).aspx and post the full response you get
Cheers
Glen

how to post on facebook wall for specific list of users using asp.net c#?

I am trying to post on specific group of users on facebook such as (close friends, or family, or college friend...) and I used the code bellow.
code that I used:
1
FacebookClient fpost1 = new FacebookClient(access_token);
fpost1.Post("/1234567890/feed", new { message = "test post"});
note: access_token is working correctly when I am doing some job before this exception.
I put my friendlist id instead of 1234567890, that you can get it from graph .../me?fields=friendlists
it did not work and gave me this error "(OAuthException - #2) An unexpected error has occurred. Please retry your request later."
2
FacebookClient fpost1 = new FacebookClient(access_token);
fpost1.Post("/me/feed", new { message = "it is very cold.", to="1234567890"});
this one work, but it post to "only me" as target.
thank you
It looks to me that what you are doing here...
FacebookClient fpost1 = new FacebookClient(access_token);
fpost1.Post("/1234567890/feed", new { message = "test post"});
is wrong. Because I believe that 1234567890 is a user-id, right? Not a friendslist-id. According to the documentation this edge/endpoint signature goes like....
/{user-id}/feed
where user-id is obviously a user id. The documentation states that...
Most nodes in the Graph API have edges that can be published to (such as Photos or Posts). All Graph API publishing is done simply with an HTTP POST request to the relevant endpoint with any necesssary parameters included. For example, if you wanted to publish a post on behalf of someone, you would make an HTTP POST request as below:
POST graph.facebook.com
/{user-id}/feed?
message={message}&
access_token={access-token}
Notice that it says "On Behalf of Someone". My understanding is that you are publishing on behalf of someone and to do that, this someone must have requested an access_token through your application. In other words, if this user hasn't logged in to your app and generated a valid access token you cannot publish on his/her wall
POST graph.facebook.com
me/feed?message="hello"&privacy={"value": "CUSTOM", "allow": "1234567890"}
where the 1234567890 is one of friendlists id

C# SMTP sent from server not on the same domain as Exchange is blank

I've just written a piece of code for a MVC website that sends a SMTP email using the .NET SmtpClient via our Exchange server. The email it sends has a HTML body with links to images and a file that are hosted on the website.
The email is sent fine when run internally on our network, but when its run from the hosted server that's not on our domin, the email comes through but the body is blank. Does anybody have any idea why? Is is because of the linked images or file that could be a potential threat and come from a server not on the domain and so is not trusted?
Here's the code that sends the email, it uses the MailDefinition class to insert a link to a file into the body that they've requested to download:
MailDefinition md = new MailDefinition();
md.From = "test#testing.com";
md.Subject = "Test Email";
md.IsBodyHtml = true;
ListDictionary replacements = new ListDictionary();
replacements.Add("REQUESTED_LINK", #"C:\MyFile.pdf");
MailMessage email = md.CreateMailMessage(mailTo, replacements, content, new System.Web.UI.Control());
SmtpClient emailClient = new SmtpClient();
emailClient.Host = "MyExchangeServer";
emailClient.Send(email);
My guess is Value for MailDefinition.BodyFileName missing from the code.
The name of the file that contains the message body text. The default is Empty.
On development or in internal sevrer BodyFileName has a some value. On hosted sevrer file is missing so email Body is empty.
see this Example for reference
Fixed, turns out the .html file containing the body of the email hadn't been deployed to the live server, and so the body of the email was blank as a result. Adding it fixed the problem, so it turns out it wasn't a security issue after all. Thanks for your help

Sending email using Smtp.mail.microsoftonline.com

The context:
We’re a small company that does not have an Exchange Server (or anyone dedicated to it) yet we still need to have/send emails.
We’ve decided to use Microsoft Online Services (MOS)
The Objective:
We have a web server (Windows Server 2003 R2 with IIS 6.0) and have deployed a C# ASP.Net MCV application.
The web application needs to send emails each time a user creates an account.
According to the documentation we need to use port (587) and make sure Transport Layer Security (TLS) enable. In addition, the FROM address being used must be of type “Authoritative” which it is when I double check via the Microsoft Online Administration Center
The code:
The C# code I have should be trivial and is the following:
SmtpClient server = new SmtpClient("Smtp.mail.microsoftonline.com");
server.Port = 587;
server.EnableSsl = true;
server.Credentials = new System.Net.NetworkCredential("xxx#domain.com", "123abc");
server.UseDefaultCredentials = false;
MailMessage mail = new MailMessage();
mail.From = new MailAddress("xxx#domain.com");
mail.To.Add("johndoe#domain.com");
mail.Subject = "test subject";
mail.Body = "this is my message body";
mail.IsBodyHtml = true;
try
{
server.Send(mail);
}
catch (Exception ex)
{
throw ex;
}
The error:
I’ve created a simple winform application with the above code to test the sending of emails…
I’ve tested the winform application locally on my computer (Windows XP) and on the Server.
In both attempt, I keep receiving the following error message:
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.1 Client was not authenticated.
After Googling for a while I still haven’t found the reason why…In addition, most of the answers I’ve found are making a reference to the Exchange Management Console which we don’t seem to have (or installed) hence why we are using Microsoft Online Services…
Questions:
1) As a paying customer of MOS, my initial understanding is that I shouldn’t have to install (or have) an Exchange Management Console on our server…in fact, this should be completely irrelevant in order to achieve my task.
2) I’ve also tried enabling TLS inside our IIS 6.0 but to no avail…
3) We are grasping at straws here because what we seem to do looks like something amazingly trivial…
4) Should we simply abandon the idea of using MOS’s SMTP server and use another one? Such as Gmail’s ? If so…then why bother paying a monthly fee for MOS?
If any one has any help/advice that can help me shed some light on this, that would be great!
Sincerely
Vince
WOW…I believe we’ve found the culprit!!!
By commenting this line of code:
//server.UseDefaultCredentials = false;
Everything started to work!
I’m now able to send emails inside and outside our domain…
What puzzles me the most is that, according to the documentation, the default value of this UseDefaultCredentials property is set to false
So…when I manually set it to false it doesn’t work but when I comment the line (which also set’s it to false because of its default value) it works!
If this is a known issue or if anyone has an answer for that, I’d be curious to know!
looking in Reflector on UseDefaultCredentials property, you can see that it also changes the trasnport.Credentials value, so when you called this property with a false value, it changed the transport credentials to null.
the problem is that you called this property after setting the credentials in the line before that,
it nullified the credentials.
so bottom line, you shouldn't set the credentials and call this property afterwise.
you can try this sample
private void Button1_Click(System.Object sender, System.EventArgs e)
{
try
{
MailMessage myMessage = new MailMessage();
SmtpClient myClient = new SmtpClient("yourserver");
myClient.Port = "587";
myClient.Host = "your server";
myClient.UseDefaultCredentials = false;
myClient.Credentials = new System.Net.NetworkCredential("username", "password");
myMessage.From = new MailAddress("sender");
myMessage.To.Add("recipient");
myMessage.Subject = "Subject email";
myMessage.Body = "body email";
myClient.EnableSsl = true;
myClient.Send(myMessage);
}
catch (Exepiton ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
Bye
5.7.1 is not an authentication issue, but a relay issue. In order to prevent anyone from using your server (or account, as the case may be) the smtp server is configured to only allow mail to users outside your domain if it is comming from an authoritive address. Verify that the address you have listed here
mail.From = new MailAddress("xxx#domain.com");
is the same as the one you are authenticating as. Also, make sure that the domain of the address listed is in the authoritive domains list.
What worked for me was what the-dude suggested Send SMTP email using System.Net.Mail via Exchange Online (Office 365) , on changing the email "from" address to be the same as the login for the stmp address
AND
doing what Vince suggested at the end Sending email using Smtp.mail.microsoftonline.com for commenting out "smtpClient.UseDefaultCredentials = false;"
Be sure to double check that your username is correct. It is not necessarily the same as your from email address. For example the from address may be "no-reply#yourdomain.com" but the username could be "mail-svc#yourdomain.onmicrosoft.com" depending no your setup and integration with Azure Active Directory etc.

Categories