SendGrid SMTP integration issue - c#

I am trying to integrate SendGrid in ASP.NET MVC application using SmtpClient and MailMessage methods on Azure.
Code:
MailMessage message = new MailMessage();
message.IsBodyHtml = true;
message.Subject = "Subject";
message.To.Add("To#MyDomain.com");
message.Body = "Body";
message.From = new MailAddress("From#MyDomain.com", "From Name");
SmtpClient client = new SmtpClient("smtp.sendgrid.net");
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("??", "SG.******");
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Port = 587; // I have tried with 25 and 2525
client.Timeout = 99999;
client.EnableSsl = false;
client.Send(message);
I end up with this issue both from C# console application and ASP.NET MVC application on Azure VM:
System.Net.Mail.SmtpException: Failure sending mail. ---> System.IO.IOException: Unable to read data from the transport connection: net_io_connectionclosed.
As per the documentation avlb on SendGrid site: https://sendgrid.com/docs/Classroom/Basics/Email_Infrastructure/recommended_smtp_settings.html
The UserName and Password has to : Use the string “apikey” for the SMTP username and use your API key for the password.
I have tried -
SendGrid UserName with which I login to their portal
The API Key from this page https://app.sendgrid.com/settings/api_keys
The password which starts with SG* which is as per their support team.
Any suggestions what am I missing or what which UserName/APIKey should I be using?
Tx!

The link says: Use the string “apikey” for the SMTP username and your API key for the password.
https://docs.sendgrid.com/for-developers/sending-email/v2-csharp-code-example#using-nets-built-in-smtp-library
The username was supposed to be "apikey" and not the actual "api key or api name"
client.Credentials = new NetworkCredential("apikey",
"<Your API Key which starts with SG.*>");
Adding "apikey" (facepalm) fixed my problem.

According to your description, I guess you may not add the VM outbound role for port 587.
I suggest you could follow below steps to add the role.
Find the network in azure vm portal.
Then find add outbound rule.
3.Add 587 port to outbound role.
Update:
I suggest you could try to use sendgrid SDK to do this.
I have create a test console application, it works well in my side.
Library: SendGrid
Codes as below:
var client = new SendGridClient("sendgridkey");
var from = new EmailAddress("send email address", "Example User");
var subject = "Sending with SendGrid is Fun";
var to = new EmailAddress("To email address", "Example User");
var plainTextContent = $"Name : aaaa";
var htmlContent = "<strong>and easy to do anywhere, even with C#</strong>";
var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
client.SendEmailAsync(msg).Wait();
int i = 0;

Related

Issue in SMTP email sending, ASP .Net mvc application hosted in Azure

I am new to azure. My asp .net MVC application hosted in azure. This application has email sending functionality. When the application is moved to azure, email functionality is not working. My error logs displays error as below:
System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Must issue a STARTTLS command first. a65sm9218660oih.6 - gsmtp
at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response)
at System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, MailAddress from, Boolean allowUnicode)
at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& exception)
at System.Net.Mail.SmtpClient.Send(MailMessage message)
Code block used to send emails
SmtpClient client = new SmtpClient(GetStringValue(EMAIL_CLIENT), GetIntValue(EMAIL_PORT))
{
Credentials = new NetworkCredential(GetStringValue(EMAIL_USER_NAME), GetStringValue(EMAIL_PASSWORD)),
EnableSsl = sslOn
};
client.Host = SettingsManager.GetStringValue("EmailClient");//smtp.gmail.com
client.Port = SettingsManager.GetIntValue("EmailPort");//587
client.DeliveryMethod = SmtpDeliveryMethod.Network;
Can anyone please help me to resolve this problem. Thank you.
Even I faced the same issue with gmail. Gmail block your emails from azure, because your app is trying to log in from a location with different timezone or different from the one you used to create the account. Check your gmail inbox and it will have an email regarding blocked login attempt.
The solution is to either login to gmail from your azure server or
check the blocked email in your inbox and add that device to verfied
devices. ie select "I recognize this activity as mine" as mentioned in
this link.
This is fully working code from an app we had at one time hosted on Azure. The email sent fine through gmail
MailMessage mail = new MailMessage();
mail.From = new MailAddress("Support#domain.com");
mail.Subject = "Subject";
mail.IsBodyHtml = true;
mail.To.Add(new MailAddress(email));
mail.Body = "Email body";
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.Credentials = new System.Net.NetworkCredential("gmail-email-address", "gmail-password");
smtp.EnableSsl = true;
smtp.Send(mail);
First check your code, there is issues on port, credentials, timeout, ...
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, "yourApplicationSpecificPassword"),
Timeout = 10000
};
using (var message = new MailMessage(fromAddress, toAddress)
{
IsBodyHtml = true,
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
Then in gmail setting, use 2 step verification -
https://myaccount.google.com/u/3/signinoptions/two-step-verification
and generate app passwd - https://myaccount.google.com/u/3/apppasswords
use generated passwd in code "yourApplicationSpecificPassword"
good luck!!

authentication error in sending mail from yahoo in c# windows application

i am trying to send email from my software using the smtp of yahoo but it shows the following error
"The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.1 Authentication required".
I know about the less secure apps setting in google but i don't know about the settings in yahoo. the same code runs fine with the gmail account credentials. here is the code for reference.
string EmailFrom = "test#yahoo.com";
string EmailTo = "test#gmail.com";
string PassWord = "test123";
string EmailHost = "smtp.mail.yahoo.com";
string status = "";
string Body = "";
MailMessage message = new MailMessage();
SmtpClient smtp = new SmtpClient();
message.From = new MailAddress(EmailFrom);
message.To.Add(new MailAddress(EmailTo));
message.Subject = "Auto Backup at test" ;
message.Body = "Backup has been taken at test on" + DateTime.Now;
Body = "Backup has been taken at test on" + DateTime.Now;
smtp.Port = 587;
smtp.Host = EmailHost;
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(EmailFrom, PassWord);
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
//ServiceLogLibrary.WriteErrorlog("Step:5");
//Library.WriteErrorlog("Before sending mail");
smtp.Send(message);
Just providing some more information here as things have changed a little since the accepted answer was posted.
Go to the account security settings (https://login.yahoo.com/account/security)
Scroll to the bottom and search for the "Manage app passwords" heading as shown below and click it to add a new app.
Select an app type and generate the password. For API apps, use "Other App".
Use this password instead of your standard mailbox password when sending emails via your SmtpClient.
You need to go to
Go to your "Account security" settings.
Select Allow apps that use less secure sign in.
To deny or turn off app access, deselect the undesired app.
Source:Temporarily allow or deny access to apps using older security sign in

Writing C# code to send an email with office 365

This seems like it should be simple to me, but I cannot get it to work. I can easily send emails with code like this:
[OperationBehavior(Impersonation = ImpersonationOption.Required)]
public static void sendEmail(string toEmail, string toName, string subject, string body)
{
MailAddress from = new MailAddress("TizzyFoe#MyCompany.com", "Mr Tizzy Foe");
const string UserName = "TizzyFoe#MyCompanyInc.com";
const string password = "ThisIsMyRealPassword";
const string host = "smtp.office365.com";
MailMessage msg = new MailMessage();
msg.To.Add(new MailAddress(toEmail, toName));
msg.From = from;
msg.Subject = subject;
msg.Body = body;
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = true;
//client.Credentials = (System.Net.ICredentialsByHost)System.Net.CredentialCache.DefaultCredentials;
//client.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
client.Credentials = new System.Net.NetworkCredential(UserName, password);
client.Port = 587;
client.Host = host;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
client.Send(msg);
}
But putting my password into code like that is bad for a variety of obvious reasons.
So what I want to do is say, okay this program is running on my laptop and I am logged in as me. So shouldn't the program be able to access my credentials. And you can see i commented out two failed attempts to do just that:
//client.Credentials = (System.Net.ICredentialsByHost)System.Net.CredentialCache.DefaultCredentials;
//client.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
both of those result in this exception:
The SMTP server requires a secure connection or the client was not
authenticated. The server response was: 5.7.57 SMTP; Client was not
authenticated to send anonymous mail during MAIL FROM
Maybe my program can only access some encrypted version of my credentials which cannot be passed to the office365 server? I have kind of a working knowledge of security concepts, but this is getting over my head.
I feel like this can't possible be that difficult. I know there are applications which can send automated emails through office 365. Right now, I'm just testing my code as a console app, but my thinking was ultimately I'd create a windows service to run it. Maybe the windows service would be able to pass credentials?

Hmailserver C# SMTP

I'm just trying to get my hmailserver to send mail from my C# program. The part that's killing me is the SSL part.
I originally got this error: The SMTP server requires a secure connection or the client was not authenticated. The server response was: SMTP authentication is required.
So I added: smtp.EnableSsl = true; and now I get Server does not support secure connections.
Here is my code, this is driving me nuts. Do I have to create my own SSL or is there a way to disable SSL on hmailserver side?
MailMessage mail = new MailMessage("jlnt#ademo.net", "com", "NEW Item", emailBody);
SmtpClient smtp = new SmtpClient("1.1.1.250");
smtp.Port = 25;
NetworkCredential login = new NetworkCredential("ja#test.net", "dg");
smtp.Credentials = login;
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Send(mail);
Ahh okay what you have to do is in HMailServer go to advanced- ip ranges. Create a new IP range for example if you 192.168.1.2, you have to make the range 192.168.1.1-192.168.1.3, then at bottom uncheck all the required smtp authentication boxes.
Annoying...
To enable secure connection to send email throught your email provider, you have to change the port number.
MailMessage mail = new MailMessage("jlnt#ademo.net", "com", "NEW Item", emailBody);
SmtpClient smtp = new SmtpClient("1.1.1.250");
//smtp.Port =25;
smtp.Port =587;
NetworkCredential login = new NetworkCredential("ja#test.net", "dg");
smtp.Credentials = login;
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Send(mail);
i was having this issue, what i did was used localhost ip and EnableSsl to false
SmtpClient smtpClient = new SmtpClient();
smtpClient.Host = "127.0.0.1";
smtpClient.Credentials = new NetworkCredential("test#123test.com", "pass123");
smtpClient.EnableSsl = false;
// then your other statements like: from, to, body, to send mail
this guide will help you setup custom NetworkCredentials in HMailServer as used above, hope helps someone.
I have stumbled on this question when trying to configure hMailServer to work to e-mail sending from C#. I have tried the following:
C# SmtpClient - does not work with implicit SSL - see this question and answers
AegisImplicitMail from here - could not make it work with UTF-8 strings (I have diacritics in my strings)
MailKit from here - very powerful and mature, no problems using it
I aimed for the following:
decent security
being able to send e-mails to mainstream e-mail providers (e.g. Google, Yahoo) and reach Inbox
being able to receive e-mails from mainstream e-mail providers
C# code
public void MailKitSend(string senderEmail, string senderName, string subject, string bodyText, string receivers, string receiversCc)
{
// no receivers, no e-mail is sent
if (string.IsNullOrEmpty(receivers))
return;
var msg = new MimeMessage();
msg.From.Add(new MailboxAddress(Encoding.UTF8, senderName, senderEmail));
msg.Subject = subject;
var bb = new BodyBuilder {HtmlBody = bodyText};
msg.Body = bb.ToMessageBody();
IList<string> receiversEmails = receivers.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries).ToList();
foreach (string receiver in receiversEmails)
msg.To.Add(new MailboxAddress(Encoding.UTF8, "", receiver));
if (!string.IsNullOrEmpty(receiversCc))
{
IList<string> receiversEmailsCc = receiversCc.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries).ToList();
foreach (string receiverCc in receiversEmailsCc)
msg.Cc.Add(new MailboxAddress(Encoding.UTF8, "", receiverCc));
}
try
{
var sc = new MailKit.Net.Smtp.SmtpClient();
if (!string.IsNullOrWhiteSpace(SmtpUser) && !string.IsNullOrWhiteSpace(SmtpPassword))
{
sc.Connect(SmtpServer, 465);
sc.Authenticate(SmtpUser, SmtpPassword);
}
sc.Send(msg);
sc.Disconnect(true);
}
catch (Exception exc)
{
string err = $"Error sending e-mail from {senderEmail} ({senderName}) to {receivers}: {exc}";
throw new ApplicationException(err);
}
}
hMailServer configuration
1) Opened ports - 25, 143, 465, 995 are opened to ensure that you can send and receive e-mail
2) TCP/IP ports configuration
SMTP / 0.0.0.0 / port 25 / no security (allow receiving start process)
SMTP / 0.0.0.0 / port 465 / SSL/TLS security (must define a SSL certificate)
POP3 / 0.0.0.0 / port 995 / SSL/TLS security (use the same SSL certificate)
3) pre C# testing
Run Diagnostics from hMailServer Administrator
Use an e-mail client that allows manual configuration of various settings such as ports for each protocol, security. I have used Thunderbird. Include sending of e-mails to external providers and receiving e-mails from them (I have tried with Gmail).
I made no changes in IP ranges and left the implicit ones (My computer and the Internet).
Although it's 7 years passed since the accepted answer was posted - I also upvoted it in the beginning - I want to emphasize that the suggested solution disables the whole authentication process which is unnecessary. The problem is the line with :
smtp.UseDefaultCredentials = false;
Just remove that line and it should work.
I post here the working solution for me (note that I'm not using SSL):
MailMessage mail = new MailMessage("a1#test.com", "foooo#gmail.com");
SmtpClient client = new SmtpClient();
client.Credentials = new NetworkCredential("a1#test.com", "test");
client.Port = 25;
client.EnableSsl = false;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = "...IPv4 Address from ipconfig...";
mail.Subject = "this is a test email.";
mail.Body = "this is my test email body";
client.Send(mail);

How to set From Address to any email other gmail in ( Sending Email in .NET Through Gmail )?

In this post Sending Email in .NET Through Gmail we have a code to send email through gmail, in the send mail we find from Field contain gmail account that I used
I use the same code but by changing the From Address to any email I want ans set gmail address in Credentials as bellow
var fromAddress = new MailAddress("AnyEmai#mailserver.com", "From Name");
var toAddress = new MailAddress("to#example.com", "To Name");
const string fromPassword = "fromPassword";
const string subject = "Subject";
const string body = "Body";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential("from#gmail.com", fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
But in the sent email gmail account still appear in From Address and AnyEmai#mailserver.com not appear ... is there any way to do that ?
It's that way by design. You have to find another way to send outbound emails so that the return address you want shows up (I've been there, there seems to be no way to spoof the from address).
Shall you check this question change sender address when sending mail through gmail in c#
I think it is related to your inquiry.
You can import an email id in your gmail account using Mail Settings >> Accounts and Import options and that can be used for sending the mails, however if you are want to use some random email id everytime to send the mails it is not possible. Gmail will treat that as a spoofing/spam and it will reset the mail address to your original mail id before sending the mail.
using System.Net;
using System.Net.Mail;
public void email_send()
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("from#gmail.com");
mail.To.Add("to#gmail.com");
mail.Subject = "Your Subject";
mail.Body = "Body Content goes here";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("c:/file.txt");
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("from#gmail.com", "mailpassword");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
There are many other mail services from which you can achieve the same but not through the gmail. Checkout the blog Send email in .NET through Gmail for sending mail using different properties.
The email address needed to be verified by gmail from the account settings.
Please find my blog post for the same describing it in detail, the steps to be followed:
http://karmic-development.blogspot.in/2013/10/send-email-from-aspnet-using-gmail-as.html
before following all the above steps, you need to authenticate your gmail account to allow access to your application and also the devices. Please check all the steps for account authentication at the following link:
http://karmic-development.blogspot.in/2013/11/allow-account-access-while-sending.html

Categories

Resources