I'm following the example from SendGrid's site and as credentials I'm pasting it what they gave me in the Azure portal. Still, I get this error message.
Message = {"Failure sending mail."}
InnerException = {"Unable to connect to the remote server"}
I'm not clear on what to do here, not even how to debug it. I'm running the code from the desktop (before I put it on the site) so I can break-point myself through it. However, to no joy...
Suggestions?
Full code below.
MailMessage mailMsg = new MailMessage();
mailMsg.To.Add(new MailAddress("[email protected]", "To Name"));
mailMsg.From = new MailAddress("[email protected]", "From Name");
mailMsg.Subject = "subject";
string text = "text body";
string html = @"<p>html body</p>";
mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(
text, null, MediaTypeNames.Text.Plain));
mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(
html, null, MediaTypeNames.Text.Html));
SmtpClient client = new SmtpClient("smtp.sendgrid.net", Convert.ToInt32(587));
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(
"[email protected]",
"LubX........pQc");
client.Credentials = credentials;
client.Send(mailMsg);
Does this happen to be a console application? I've been testing SendGrid and found that when I try to send an email from a Console application the emails are never sent. However, when I tried it from a web application (using the same exact sending code) the emails are sent. I have no explanation for why the console application does not work.
I was able to get a SendGrid email send to happen successfully from a Console application using the SendGrid v3 C# API.
I first needed to import the SendGrid C# library via NuGet using the Package Manager Console in Visual Studio:
PM> Install-Package SendGrid
Then, my code:
using SendGrid;
using SendGrid.Helpers.Mail;
using System.Threading.Tasks;
// ...
public static async Task SendEmailViaSendGrid(string to, string from, string subject, string body)
{
// Generated from https://app.sendgrid.com/settings/api_keys
// TODO: Store this somewhere secure -- not in version control.
string apiKey = "YOUR_PRIVATE_SENDGRID_API_KEY_GOES_HERE";
dynamic sendGridClient = new SendGridAPIClient(apiKey);
Email fromEmail = new Email(from);
Email toEmail = new Email(to);
Content content = new Content("text/plain", body);
Mail mail = new Mail(fromEmail, subject, toEmail, content);
dynamic response = await sendGridClient.client.mail.send.post(requestBody: mail.Get());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With