Send Email using SMTP via gmail - c#

I'm working in ASP.Net Core and trying to send email using smtp client from gmail. Have following code but it's not working
Have seen following post as well but it doesn't work
http://dotnetthoughts.net/how-to-send-emails-from-aspnet-core/
It thorws following error
System.NotSupportedException: The SMTP server does not support authentication
var emailMessage = new MimeMessage();
emailMessage.From.Add(new MailboxAddress("From Name", "fromEmail#gmail.com"));
emailMessage.To.Add(new MailboxAddress("To Name", "toEmail#gmail.com"));
emailMessage.Subject = subject;
var bodyBuilder = new BodyBuilder();
bodyBuilder.HtmlBody = message;
emailMessage.Body = bodyBuilder.ToMessageBody();
var client = new SmtpClient();
try
{
await client.ConnectAsync("smtp.gmail.com", 25, SecureSocketOptions.None).ConfigureAwait(false);
client.AuthenticationMechanisms.Remove("XOAUTH2");
await client.AuthenticateAsync("fromEmail#gmail.com", "fromPassword"); //error occurs here
await client.SendAsync(emailMessage).ConfigureAwait(false);
await client.DisconnectAsync(true);
await client.DisconnectAsync(true).ConfigureAwait(false);
}
catch(Exception e)
{
}

The NotSupportedException is thrown because GMail does not support authentication without using an SSL/TLS connection because it only supports non-encrypted password-based authentication mechanisms.
I would recommend connecting like this:
client.ConnectAsync("smtp.gmail.com", 587, SecureSocketOptions.StartTls)
Hope that helps.

Related

How to send an email with Mailkit

I'm using Mailkit in Asp.net Core to receive email from other but To and From email is the same but in debug To and From have the correct emails?
This is my code what's wrong?/?
MimeMessage emailMessage = new MimeMessage() ;
emailMessage.From.Add(MailboxAddress.Parse(_userIdentity.Email));
emailMessage.To.Add(MailboxAddress.Parse("my email"));
emailMessage.Subject = "Support email";
BodyBuilder emailBodyBuilder = new BodyBuilder();
emailBodyBuilder.TextBody = message;
emailMessage.Body = emailBodyBuilder.ToMessageBody();
var smtp = new MailKit.Net.Smtp.SmtpClient();
smtp.Connect("smtp.gmail.com" , 587, SecureSocketOptions.StartTls);
smtp.Authenticate("my email", "*********");
await smtp.SendAsync(emailMessage);
smtp.Disconnect(true);
Let me guess. You are setting the From address to an address that does not match your #gmail.com address.
When you send the message, the From address gets replaced with your #gmail.com address.
This is because smtp.gmail.com rewrites the From header in order to prevent you from spoofing another person's email address.

Emails not sending with Mailkit or .net smtp client

The native MVC UserManager.sendasync works great. But when i instantiate an Email service and try to send an email ... no dice. I made a php script to send the email. Works beatuifully super easy. I also tried downloading and using Mailkit... no dice. Im not sure what to do here. No error message
var mimeMessage = new MimeMessage();
mimeMessage.From.Add(new MailboxAddress("System", "system#my.hypertarget.io"));
mimeMessage.To.Add(new MailboxAddress("Jason", "unblockgames#gmail.com"));
mimeMessage.Subject = "Test";
mimeMessage.Body = new TextPart("plain"){Text = message};
using (var client = new SmtpClient())
{
// For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
client.Connect("relay-hosting.secureserver.net", 25, false);
client.Capabilities &= ~SmtpCapabilities.Pipelining;
client.Send(mimeMessage);
client.Disconnect(true);
}

Send Email in C# using NTLM

I need to send email using NTLM, currently, I'm using the following code to send email
SmtpClient objSmtpClient;
System.Net.NetworkCredential objNetworkCredential;
objSmtpClient = new SmtpClient("10.xxx.xxx.xxx", 587);
objSmtpClient.EnableSsl = true;
objNetworkCredential = new System.Net.NetworkCredential(userName, password);
try
{
string to = txtto.Text;
MailMessage objMailMessage = new MailMessage();
objMailMessage.From = new MailAddress("from#email.com", "sendername");
objMailMessage.To.Add(new MailAddress("to#email.com"));
objMailMessage.Subject = "subject";
objMailMessage.Body = "body";
objMailMessage.IsBodyHtml = true;
objSmtpClient.EnableSsl = true;
objSmtpClient.UseDefaultCredentials = true;
objSmtpClient.Credentials = objNetworkCredential;
objSmtpClient.Send(objMailMessage);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + " INNER EXCEPTION > "+ex.InnerException +" DATA > "+ex.Data);
}
The Above code works if I try to change the port to 25 and EnableSSL to false, But when I try to send it using 587 and setting EnableSSL to true it doesn't work.
I'm getting the following error, sometimes I get an Invalid Certificate error.
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.1 Client was not authenticated.
I am also getting this error
I think the problem is with Authentication, how can I force to use NTLM
I talked with the IT team they installed a tool on my pc to check email, using that tool email was sent successfully.
The following are the setting which he applied in that tool
Can someone please help
I was testing, I had the same problem, I fixed it by disabling SSL security
SC.EnableSsl = false;

How to send email by using MailKit?

According to the new google politics https://googleonlinesecurity.blogspot.de/2014/04/new-security-measures-will-affect-older.html I can't sent an email. "Less secure apps" are considered for google the application which don't use OAuth 2.0.
I would like to use MailKit to solve this problem
var message = new MimeMessage();
message.From.Add(new MailboxAddress("Joey Tribbiani", "noreply#localhost.com"));
message.To.Add(new MailboxAddress("Mrs. Chanandler Bong", "mymail#gmail.com"));
message.Subject = "How you doin'?";
message.Body = new TextPart("plain"){ Text = #"Hey" };
using (var client = new SmtpClient())
{
client.Connect("smtp.gmail.com", 587);
////Note: only needed if the SMTP server requires authentication
client.Authenticate("mymail#gmail.com", "mypassword");
client.Send(message);
client.Disconnect(true);
}
But I have got An exception of type 'MailKit.Security.AuthenticationException' occurred in MailKit.dll but was not handled in user code.Additional information: Authentication failed.
I don't want to change my security settings. Because I want that everything will be secure. That's why I start to use MailKit rather than System.Net.Mail
How can I fix it?
The first thing you need to do is follow Google's instructions for obtaining OAuth 2.0 credentials for your application.
Once you've done that, the easiest way to obtain an access token is to use Google's Google.Apis.Auth library:
var certificate = new X509Certificate2 (#"C:\path\to\certificate.p12", "password", X509KeyStorageFlags.Exportable);
var credential = new ServiceAccountCredential (new ServiceAccountCredential
.Initializer ("your-developer-id#developer.gserviceaccount.com") {
// Note: other scopes can be found here: https://developers.google.com/gmail/api/auth/scopes
Scopes = new[] { "https://mail.google.com/" },
User = "username#gmail.com"
}.FromCertificate (certificate));
//You can also use FromPrivateKey(privateKey) where privateKey
// is the value of the field 'private_key' in your serviceName.json file
bool result = await credential.RequestAccessTokenAsync (cancel.Token);
// Note: result will be true if the access token was received successfully
Now that you have an access token (credential.Token.AccessToken), you can use it with MailKit as if it were the password:
using (var client = new SmtpClient ()) {
client.Connect ("smtp.gmail.com", 587);
// use the OAuth2.0 access token obtained above
var oauth2 = new SaslMechanismOAuth2 ("mymail#gmail.com", credential.Token.AccessToken);
client.Authenticate (oauth2);
client.Send (message);
client.Disconnect (true);
}
Update:
The above solution is for what Google refers to as "Service Accounts" that are used for server-to-server communication, but if you want OAuth2 support for standard Phone or Desktop apps, for example, you'll need to follow the directions I've written here: https://github.com/jstedfast/MailKit/blob/master/GMailOAuth2.md
Tested following code and works for me:
// STEP 1: Navigate to this page https://www.google.com/settings/security/lesssecureapps & set to "Turn On"
var message = new MimeMessage();
message.From.Add(new MailboxAddress("Joey Tribbiani", "YOU_FROM_ADDRESS#gmail.com"));
message.To.Add(new MailboxAddress("Mrs. Chanandler Bong", "YOU_TO_ADDRESS#gmail.com"));
message.Subject = "How you doin'?";
message.Body = new TextPart("plain")
{
Text = #"Hey Chandler,I just wanted to let you know that Monica and I were going to go play some paintball, you in?-- Joey"
};
using (var client = new SmtpClient())
{
client.Connect("smtp.gmail.com", 587);
// Note: since we don't have an OAuth2 token, disable
// the XOAUTH2 authentication mechanism.
client.AuthenticationMechanisms.Remove("XOAUTH2");
// Note: only needed if the SMTP server requires authentication
client.Authenticate("YOUR_GMAIL_NAME", "YOUR_PASSWORD");
client.Send(message);
client.Disconnect(true);
}

sending email failed in .net when using google smtp server

I am trying to send email like this
var fromAddress = new MailAddress("fromaddress", "From Name");
var toAddress = new MailAddress("toaddress", "To Name");
const string fromPassword = "password";
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(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
Console.WriteLine("Sent");
Console.ReadLine();
but it gives this error .
The SMTP server requires a secure connection or the client was not authenticated.
The server response was: 5.5.1 Authentication Required.
I am sing this code in simple console application on my local host . So whats the issue in my code ?
Update
I changed fromAddress email and it send email successfully . But i don't receive any email in my toAddress email's inbox/Spam .
Try to add DeliveryMethod = SmtpDeliveryMethod.Network when creating SmtpClient.
See post:
https://stackoverflow.com/a/489594/1432770
There is a variety of reasons for this discussed here:
Sending email through Gmail SMTP server with C#
Your code in the first link has worked for me.
Do you use two steps verification?
You need to sign in using application-specific passwords: https://support.google.com/accounts/answer/185833?hl=en
Your code worked for me too!

Categories