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);
}
Related
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;
This question might be flagged as a duplicate But it is not. Because the code sends email successfully when using normal gmail account that ends with #gmail.com. The problem only happens when using G suit accounts that are custom and ends with #yourdomainname.com.
I am using this code to send email. My account has two-step verification so I created an app password for verification and use it to send email.
using (var mm = new MailMessage(PrivateSettings.SenderEmail, message.Destination))
{
mm.Subject = message.Subject;
mm.Body = message.Body;
mm.IsBodyHtml = true;
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
EnableSsl = true
};
var networkCred = new NetworkCredential(PrivateSettings.SenderEmail, PrivateSettings.EmailPassword);
smtp.UseDefaultCredentials = true;
smtp.Credentials = networkCred;
smtp.Port = 587;
smtp.Send(mm);
}
The above code sends email successfully when I use my normal gmail account which is se.natnael.zeleke#gmail.com.
But when I use one of my G Suit account , connect#tatarri.com , to send email it fails and shows this error message.
So my question is; is their additional configuration that should be done for G suit gmail accounts.
Additional Info.
I configured both email accounts to use app password. connect#tatarri.com is also registered as admin in my G suit account.
Both email accounts have their IMAP enabled in settings.
I bought tatarri.com domain name from namecheap.
Thank you.
The line:
smtp.UseDefaultCredentials = true;
Tells the SMTP client to use the default credentials of the currently logged in user. This is what you would use for a client application.
In your case, you want to specify credentials other than the current user's, so set it to false:
smtp.UseDefaultCredentials = false;
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.
This question already has answers here:
Sending email through Gmail SMTP server with C#
(31 answers)
Closed 9 years ago.
I am New in Asp.net, i need to send email from Asp.net using my Outlook.
I have one button in asp and when i click button(send) i want to send email.
I tried to use Hotmail and Gmail but remote server in blocked.
If you don't understand my question please tell me.
I tried this:
var smtpClient = new SmtpClient
{
Host = "outlook.mycompany.local",
UseDefaultCredentials = false,
Credentials = new NetworkCredential("myEmail#mycommpany.com", "myPassword")
};
var message = new System.Net.Mail.MailMessage
{
Subject = "Test Subject",
Body = "FOLLOW THE WHITE RABBIT",
IsBodyHtml = true,
From = new MailAddress("myemail#mycommapny.com")
};
// you can add multiple email addresses here
message.To.Add(new MailAddress("friendEmail#Company.com"));
// and here you're actually sending the message
smtpClient.Send(message);
}
Exeption Show: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.1 Client was not authenticated
Please how can i do that ?
Sending outbound email from an ASP.net web site can be problematic. Even if you get the SMTP information right, you still have to deal with:
Sender Policy Framework (SPF)
Whitelists/Blacklists
Validation
Bouncebacks
It's very difficult to do this yourself, which is why you might want to consider using a service provider instead. You simply use their API (often a REST call), and they do the rest. Here are three such providers:
SendGrid
Mandrill
Mailgun
Mandrill has a low-end free plan, and so does SendGrid if you are using it with Windows Azure. And they are all reasonably affordable, even for the larger plans.
I highly recommend using one of these with their own API instead of using System.Net.Mail yourself. But if you want, they also can act as an SMTP relay for you so you can use their SMTP servers and keep your System.Net.Mail code intact.
First of all get the company SMTP server settings (from your sys admins I guess), then you can do something like this:
// setting up the server
var smtpClient = new SmtpClient
{
Host = "your.company.smtp.server",
UseDefaultCredentials = false,
EnableSsl = true, // <-- see if you need this
Credentials = new NetworkCredential("account_to_use", "password")
};
var message = new MailMessage
{
Subject = "Test Subject",
Body = "FOLLOW THE WHITE RABBIT",
IsBodyHtml = true,
From = new MailAddress("from#company.com")
};
// you can add multiple email addresses here
message.To.Add(new MailAddress("neo#matrix.com"));
// and here you're actually sending the message
smtpClient.Send(message);
you can use this function. and one thing you have to store you email smtp login and password in web config file
/// <summary>
/// Send Email
/// </summary>
/// <param name="strFrom"></param>
/// <param name="strTo"></param>
/// <param name="strSubject"></param>
/// <param name="strBody"></param>
/// <param name="strAttachmentPath"></param>
/// <param name="IsBodyHTML"></param>
/// <returns></returns>
public Boolean sendemail(String strFrom, string strTo, string strSubject, string strBody, string strAttachmentPath, bool IsBodyHTML)
{
Array arrToArray;
char[] splitter = { ';' };
arrToArray = strTo.Split(splitter);
MailMessage mm = new MailMessage();
mm.From = new MailAddress(strFrom);
mm.Subject = strSubject;
mm.Body = strBody;
mm.IsBodyHtml = IsBodyHTML;
//mm.ReplyTo = new MailAddress("replyto#xyz.com");
foreach (string s in arrToArray)
{
mm.To.Add(new MailAddress(s));
}
if (strAttachmentPath != "")
{
try
{
//Add Attachment
Attachment attachFile = new Attachment(strAttachmentPath);
mm.Attachments.Add(attachFile);
}
catch { }
}
SmtpClient smtp = new SmtpClient();
try
{
smtp.Host = ConfigurationManager.AppSettings["MailServer"].ToString();
smtp.EnableSsl = true; //Depending on server SSL Settings true/false
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = ConfigurationManager.AppSettings["MailUserName"].ToString();
NetworkCred.Password = ConfigurationManager.AppSettings["MailPassword"].ToString();
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;//Specify your port No;
smtp.Send(mm);
return true;
}
catch
{
mm.Dispose();
smtp = null;
return false;
}
}
Try Amazon Simple Email Service (http://aws.amazon.com/ses/). If you're new to Amazon Web Services (AWS) there might be a learning curve. However, once you're familiar with their SDK which can be found on Nuget (AWSSDK) the process is very straight-forward (Amazon does have a lot of little wrapper classes which can be quirky).
So, to answer the question "How to send email?", it looks something like:
var fromAddress = "from#youraddress.com";
var toAddresses = new Amazon.SimpleEmail.Model.Destination("someone#somedestination.com");
var subject = new Amazon.SimpleEmail.Model.Content("Message");
var body= new Body(new Amazon.SimpleEmail.Model.Content("Body"));
var message = new Message(subject , body);
var client = ConfigUtility.AmazonSimpleEmailServiceClient;
var request= new Amazon.SimpleEmail.Model.SendEmailRequest();
request.WithSource(fromAddress)
.WithDestination(toAddresses)
.WithMessage(message );
try
{
client.SendEmail(request);
}
catch (Amazon.SimpleEmail.AmazonSimpleEmailServiceException sesError)
{
throw new SupplyitException("There was a problem sending your email", sesError);
}
You can refer to below links:
http://www.codeproject.com/Tips/371417/Send-Mail-Contact-Form-using-ASP-NET-and-Csharp
send email asp.net c#
I hope it will help you. :)
I am trying to send an email using the following very standard code. However, I get the error that follow...
MailMessage message = new MailMessage();
message.Sender = new MailAddress("sen#der.com");
message.To.Add("reci#pient.com");
message.Subject = "test subject";
message.Body = "test body";
SmtpClient client = new SmtpClient();
client.Host = "mail.myhost.com";
//client.Port = 587;
NetworkCredential cred = new NetworkCredential();
cred.UserName = "sen#der.com";
cred.Password = "correct password";
cred.Domain = "mail.myhost.com";
client.Credentials = cred;
client.UseDefaultCredentials = false;
client.Send(message);
Mailbox unavailable. The server
response was: No such
user here.
This recipient email address definitely works. To make this account work I had to do some special steps in outlook. Specifically, I had to do change account settings -> more settings -> outgoing server -> my outgoing server requires authentication & use same settings. I am wondering if there is some other strategy.
I think the key here is that my host is Server Intellect and I know that some people on here use them so hopefully someone else has been able to get through this. I did talk to support but they said with coding issues I am on my own :o
try this...
NetworkCredential cred = new NetworkCredential();
cred.UserName = "sen#der.com";
cred.Password = "correct password";
//cred.Domain = "mail.myhost.com";
... you should not need to provide the .Domain unless you are using Kerberos or some other complex authentication.
Edit...
Check out my extended answer. It has an example of how to send an email with authentication. It's also has SSL enabled so you may need to remove that part.
there is no mailbox called sen#der.com on server mail.myhost.com, check that