I have a problem trying to send email (gmail) it won't allow me to send email if I didn't have the 'allow less secure app' turned on. What am I doin wrong?
try
{
smtpClient.Host = mServer;
smtpClient.Port = mPort;
smtpClient.EnableSsl = isenableSsl;
//Input new time out
if (mTimeout > 0)
{
smtpClient.Timeout = mTimeout;
}
//Check Authentication Mode
if (isAuthentication)
{
//Create Network Credentail if SMTP Server Turn On Authentication Mode
NetworkCredential credentials = new NetworkCredential();
credentials.UserName = mUserName;
credentials.Password = mPassword;
smtpClient.Credentials = credentials;
smtpClient.UseDefaultCredentials = false;
}
else
{
smtpClient.UseDefaultCredentials = true;
}
//Configuration Mail Information
if (string.IsNullOrEmpty(mDisplay)) mailMessage.From = new MailAddress(mFrom);
else mailMessage.From = new MailAddress(mFrom, mDisplay);
mailMessage.Sender = new MailAddress(mFrom);
mailMessage.ReplyTo = new MailAddress(mFrom);
//Set To Email Information
if (ToEmails.Count != 0)
{
mailMessage.To.Clear();
foreach (string mail in ToEmails)
{
mailMessage.To.Add(mail);
}
}
//Set Cc Email Information
mailMessage.CC.Clear();
foreach (string mail in CcEmails)
{
mailMessage.CC.Add(mail);
}
//Set Bcc Email Information
mailMessage.Bcc.Clear();
foreach (string mail in BccEmails)
{
mailMessage.Bcc.Add(mail);
}
//Set Mail Information
mailMessage.Subject = mSubject;
mailMessage.Body = mBody;
//Configuration Mail Option
mailMessage.IsBodyHtml = isBodyHtml;
mailMessage.SubjectEncoding = mSubjectEncoding;
mailMessage.BodyEncoding = mBodyEncoding;
mailMessage.Priority = mPriority;
mailMessage.DeliveryNotificationOptions = mDeliveryNotificationOptions;
//Clear Attachment File
mailMessage.Attachments.Clear();
//Add Attachments Internal File
AddAttachImage(ref mailMessage);
//Add Attachments External File
if (attachmentFiles.Count > 0)
{
AddAttachFile(ref mailMessage);
}
//Link Event Handler
smtpClient.SendCompleted += new SendCompletedEventHandler(smtpClient_SendCompleted);
//Send Message Fuction
SetLogfileSendEmail(smtpClient, mailMessage);
ServicePointManager.ServerCertificateValidationCallback =
delegate(object s, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{ return true; };
smtpClient.Send(mailMessage);
}
catch (Exception ex)
{
strInformation.Append("(Error) Method smtpClient_SendCompleted : " + ex.Message);
WriteLogFile();
throw new Exception("SMTP Exception: " + ex.Message);
}
}
It is also giving me this
SMTP Exception: The SMTP server requires a secure connection or the client was not authenticated.
The server response was: 5.7.0 Authentication Required.
I want to be able to send email without having to turn on the "allow less secure app" option on gmail account.
Is there any other way for third party apps to send emails without having to do 'allow less secure apps' ??
If you (sender) use gmail provider, try to activate this option
https://www.google.com/settings/security/lesssecureapps
Related
Sending mails doesn't work. I'm not sure if it's something with client settings or mail server...
When using Gmail SMTP server I got "Connection closed" exception, when changing port to 587 I get "Authentication required" message. What's more interesting when changing SMTP server to something different (smtp.poczta.onet.pl) I get "Time out" exception after ~100s
Here's the code:
protected void SendMessage(object sender, EventArgs e)
{
// receiver address
string to = "******#student.uj.edu.pl";
// mail (sender) address
string from = "******#gmail.com";
// SMTP server address
string server = "smtp.gmail.com";
// mail password
string password = "************";
MailMessage message = new MailMessage(from, to);
// message title
message.Subject = TextBox1.Text;
// message body
message.Body = TextBox3.Text + " otrzymane " + DateTime.Now.ToString() + " od: " + TextBox2.Text;
SmtpClient client = new SmtpClient(server, 587);
client.Credentials = new System.Net.NetworkCredential(from, password);
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.EnableSsl = true;
try
{
client.Send(message);
// ui confirmation
TextBox3.Text = "Wysłano wiadmość!";
// disable button
Button1.Enabled = false;
}
catch (Exception ex)
{
// error message
TextBox3.Text = "Problem z wysłaniem wiadomości (" + ex.ToString() + ")";
}
}
I've just read that google don't support some less secure apps (3rd party apps to sign in to Google Account using username and password only) since 30/05/22. Unfortunately can't change it because I have two-stage verification account. Might it be connected? Or is it something with my code?
Gmail doesn't allow, or want you to do that with passwords anymore. They ask you to create a credentials files and then use a token.json to send email.
Using their API from Google.Apis.Gmail.v1 - from Nuget. Here is a method I made and test that is working with gmail.
void Main()
{
UserCredential credential;
using (var stream =
new FileStream(#"C:\credentials.json", FileMode.Open, FileAccess.Read))
{
// The file token.json stores the user's access and refresh tokens, and is created
// automatically when the authorization flow completes for the first time.
string credPath = "token.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Gmail API service.
var service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Define parameters of request.
UsersResource.LabelsResource.ListRequest request = service.Users.Labels.List("me");
// List labels.
IList<Label> labels = request.Execute().Labels;
Console.WriteLine("Labels:");
if (labels != null && labels.Count > 0)
{
foreach (var labelItem in labels)
{
Console.WriteLine("{0}", labelItem.Name);
}
}
else
{
Console.WriteLine("No labels found.");
}
//Console.Read();
var msg = new Google.Apis.Gmail.v1.Data.Message();
MimeMessage message = new MimeMessage();
message.To.Add(new MailboxAddress("", "toemail.com"));
message.From.Add(new MailboxAddress("Some Name", "YourGmailGoesHere#gmail.com"));
message.Subject = "Test email with Mime Message";
message.Body = new TextPart("html") {Text = "<h1>This</h1> is a body..."};
var ms = new MemoryStream();
message.WriteTo(ms);
ms.Position = 0;
StreamReader sr = new StreamReader(ms);
string rawString = sr.ReadToEnd();
byte[] raw = System.Text.Encoding.UTF8.GetBytes(rawString);
msg.Raw = System.Convert.ToBase64String(raw);
var res = service.Users.Messages.Send(msg, "me").Execute();
res.Dump();
}
static string[] Scopes = { GmailService.Scope.GmailSend, GmailService.Scope.GmailLabels, GmailService.Scope.GmailCompose, GmailService.Scope.MailGoogleCom};
static string ApplicationName = "Gmail API Send Email";
Enable 2FA on your email and generate a password for your application using the link. As far as I know, login and password authorization using unauthorized developer programs is no longer supported by Google.
Can you ping the smpt server from your machine or the machine you deploy the code from? THis could be a DNS issue.
I am using C# to send email using SMTP and gmail server.
Below is the code I am using for sending email. I encounter a few errors i.e.
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.
public static bool SendEmail(string from, string[] to, string[] cc, string[] bcc, string subject, string body, bool isBodyHtml, List<Attachment> attachmentList)
{
try
{
var mailMessage = new MailMessage();
var smtpClient = new SmtpClient();
mailMessage.From = new MailAddress(from);
mailMessage.To.Add(new MailAddress(string.Join(",", to)));
if (cc != null && cc.Any())
{
mailMessage.CC.Add(new MailAddress(string.Join(",", cc)));
}
if (bcc != null && bcc.Any())
{
mailMessage.Bcc.Add(new MailAddress(string.Join(",", bcc)));
}
mailMessage.Subject = subject;
mailMessage.Body = body;
mailMessage.IsBodyHtml = isBodyHtml;
if (attachmentList != null)
{
foreach (var attachment in attachmentList)
{
mailMessage.Attachments.Add(attachment);
}
}
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587; //465
smtpClient.Credentials = new System.Net.NetworkCredential("username#email.com", "passsword");
smtpClient.EnableSsl = true;
smtpClient.Send(mailMessage);
return true;
}
catch (Exception ex)
{
return false;
}
}
What am I doing wrong and how do I use gmail to send email.
You haven't set UseDefaultCredentials to false, so despite the fact you have provided credentials, the application is still trying to use your windows credentials to log into the SMTP. Try the below:
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new System.Net.NetworkCredential("username#email.com", "passsword");
UseDefaultCredentials needs to be set to false before you set the new network credentials.
If you are sure that your Username and Password are correct and you are still getting the error then it means that Gmail has blocked your application.
Try turning it on from here Grant Access to Less Secure Apps
I wrote a simple application for windows to send some emails to members of my mailing list.
The program uses my gmail account to send via SMTP. I do not want my customers having that account however, I want them to see instead the corporate email.
I sent myself some emails to test, but the emails I am recieving are showing sent from the email account Ive logged in with at google. Any ideas?
The mail function:
public void SendEmail()
{
//smtp host and port for gmail
string host = txtHost.Text;
int port;
if (!Int32.TryParse(txtPort.Text, out port))
{
MessageBox.Show("Please enter a valid port number.");
return;
}
//compose email
MailMessage msg = new MailMessage();
msg.Sender = new MailAddress(txtFrom.Text, txtFrom.Text);
msg.From = new MailAddress(txtFrom.Text, txtFrom.Text);
msg.To.Add(txtTo.Text);
msg.Subject = txtSubject.Text;
msg.Body = rTxtMessage.Text;
msg.IsBodyHtml = chkHtml.Checked;
//msg.From = new MailAddress(txtFrom.Text, txtFrom.Text);
//create smtp client
SmtpClient smtp = new SmtpClient(host, port);
//TODO: Move constants to the NetworkCredentials call
string username = SMTP_USERNAME;
string password = SMTP_PASSWORD;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(username, password);
smtp.EnableSsl = true;
try
{
//Send email
smtp.Send(msg);
}
catch (Exception exp)
{
//Log if any errors occur
MessageBox.Show(exp.Message);
}
}
And the application and result screenshots:
You should set:
msg.Sender
to your Company address.
i have a mail account on the Exchange Online service. Now i'm trying to test if i am able to send mails to customers ( on varoius domains and on Microsoft Office 365) through c# application
I tried implementing the below code but i am getting the error
"The remote certificate is invalid according to the validation
procedure."
MailMessage mail = null;
mail = new MailMessage();
string[] strToList = "abc#gmail.com"
foreach (string strID in strToList)
{
if (strID != null)
{
mail.To.Add(new MailAddress(strID));
}
}
mail.From = "demo#onmicrosoft.com";
mail.Subject = "testing"
mail.IsBodyHtml = true;
mail.Body = "mail body";
SmtpClient client = new SmtpClient("smtp.outlook.office365.com");
client.Port = 587;
client.EnableSsl = true;
client.UseDefaultCredentials = false;
NetworkCredential cred = new System.Net.NetworkCredential("demo#onmicrosoft.com", "mypassword");
client.Credentials = cred;
client.Send(mail);
Please advice if i am doing anything wrong.
Thanks a lot in advance.
this works for me ( edited from source )
ThreadPool.QueueUserWorkItem(t =>
{
SmtpClient client = new SmtpClient("smtp.office365.com",587);
client.EnableSsl = true;
client.Credentials = new System.Net.NetworkCredential("xxx#yyy.com", "password");
MailAddress from = new MailAddress("xxx#yyy.com", String.Empty, System.Text.Encoding.UTF8);
MailAddress to = new MailAddress("xxx#yyy.com");
MailMessage message = new MailMessage(from, to);
message.Body = "The message I want to send.";
message.BodyEncoding = System.Text.Encoding.UTF8;
message.Subject = "The subject of the email";
message.SubjectEncoding = System.Text.Encoding.UTF8;
// Set the method that is called back when the send operation ends.
client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
// The userState can be any object that allows your callback
// method to identify this send operation.
// For this example, I am passing the message itself
client.SendAsync(message, message);
});
private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
{
// Get the message we sent
MailMessage msg = (MailMessage)e.UserState;
if (e.Cancelled)
{
// prompt user with "send cancelled" message
}
if (e.Error != null)
{
// prompt user with error message
}
else
{
// prompt user with message sent!
// as we have the message object we can also display who the message
// was sent to etc
}
// finally dispose of the message
if (msg != null)
msg.Dispose();
}
In some cases the TLS authentication may cause problems in using smtp.office365.com as SMTP from c#.
Try the following line before the Send(msg) statement (overriding .TargetName):
client.TargetName = "STARTTLS/smtp.office365.com";
This one works for me
This is also best way to send Mail. I have tried it in my project and working fine.
SmtpClient client = new SmtpClient("smtp.office365.com", 587);
client.EnableSsl = true;
client.Credentials = new System.Net.NetworkCredential("From#mail.com", "sdsd#12345");
MailAddress from = new MailAddress("From Address Ex From#mail.com", String.Empty, System.Text.Encoding.UTF8);
MailAddress to = new MailAddress("From Address Ex To#mail.com");
MailMessage message = new MailMessage(from, to);
message.Body = "This is your body message";
message.BodyEncoding = System.Text.Encoding.UTF8;
message.Subject = "Subject";
message.SubjectEncoding = System.Text.Encoding.UTF8;
client.Send(message);
Try smtp.office365.com instead of smtp.outlook.office365.com
Try to use:
ServicePointManager.ServerCertificateValidationCallback =
(sender, certificate, chain, sslPolicyErrors) => true;
This code will allow you to accept invalid certificates.
As Ori Nachum mention in the comment: this is a very BAD practice, and should only use for testing purposes. It is a security risk!
The 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
often happens when associated user account password is expired or account is locked. Try set "Never expire user password" in Active Directory, if it does not breach your company password policy :) This happened to me while testing with o365 Exchange Online A/c.
Try setting:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
It will ensure the Service's SecurityPoint is TLS.
Please notice an answer here offered setting
ServicePointManager.ServerCertificateValidationCallback =
(sender, certificate, chain, sslPolicyErrors) => true;
May be good for testing purposes - but it's a major security risk!
Do not use with a prod account or in prod environment.
var Client = new SmtpClient("smtp.office365.com", 587);
Client.EnableSsl = true;
Client.Credentials = new System.Net.NetworkCredential("mail", "pass");
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
I successfully send mail with code
I am trying to send email to some of my colleagues using a program. This program is working fine at my own desktop but is giving an error
Bad sequence of commands. The server response was: You must authenticate first (#5.5.1)
on one of our servers in remote location. Can someone point out the error I have tried to change the position of the line of authentication. And I am not able to deduce much from the error. The same username and password are being used at both locations.
public static Boolean sendemail(String strFrom, string strTo, string strCC, string strBCC, string strReplyTO, string strSubject, string strBody, string strAttachmentPath, bool IsBodyHTML)
{
//Array arrToArray;
//char[] splitter = { ';' };
//arrToArray = strTo.Split(splitter);
MailMessage mm = new MailMessage();
bool flag = isEmailsString(strFrom);
if (flag)
{
mm.From = new MailAddress(strFrom);
}
flag = isEmailsString(strTo);
if (flag)
{
mm.To.Add(strTo);
}
flag = isEmailsString(strCC);
if (flag)
{
mm.CC.Add(strCC);
}
flag = isEmailsString(strBCC);
if (flag)
{
mm.Bcc.Add(strBCC);
}
flag = Regex.IsMatch(strReplyTO.Trim(), #"^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
if (strReplyTO != null)
{
if (flag)
{
mm.ReplyTo = new MailAddress(strReplyTO);
}
}
if (strSubject != null)
{
mm.Subject = strSubject;
}
mm.IsBodyHtml = IsBodyHTML;
if (!string.IsNullOrEmpty(strAttachmentPath))
{
Array attachmentArray;
char[] attachSplitter = { ',' };
attachmentArray = strAttachmentPath.Split(attachSplitter);
foreach (string s in attachmentArray)
{
string st = s.Trim();
if (!string.IsNullOrEmpty(st))
{
Attachment attach = new Attachment(st);
// Add the file attachment to this e-mail message.
mm.Attachments.Add(attach);
//strBodyFinal.Append(Environment.NewLine+"Go to the following link for more information"+Environment.NewLine);
//strBodyFinal.Append(st);
}
}
}
if (strBody != null)
{
mm.Body = strBody;
}
//foreach (string s in arrToArray)
// {
// mm.To.Add(new MailAddress(s));
// }
SmtpClient smtp = new SmtpClient();
try
{
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = "my user name";
NetworkCred.Password = "my password";
smtp.Credentials = NetworkCred;
smtp.Host = "my company mail site";//host of your mail account
//smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Port = 2525;//port no of your mail account
smtp.Timeout = 500000;
smtp.Send(mm);
return true;
}
catch (Exception ex)
{
mm.Dispose();
smtp = null;
Console.WriteLine(ex.Message, ex.StackTrace);
return false;
}
}
I searched a lot about the issue and finding different interpretations for the error message like: MAIL command issued after BDAT command so it says Bad sequence of commands. But actually the problem was sorted when I changed my code above to
SmtpClient smtp = new SmtpClient();
smtp.UseDefaultCredentials = false; // <<<you need THIS
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = "my user name";
NetworkCred.Password = "my password";
smtp.Credentials = NetworkCred;
smtp.Host = "my company mail site";//host of your mail account
smtp.Port = 2525;//port no of your mail account
smtp.Timeout = 500000;
smtp.Send(mm);
Notice that UseDefaultCredentials is set to false before the Credentials are assigned new credentials. This change of sequence of setting default to false magically worked for me.
Just for the record Network Solution SMTP seems to NEED the username in lowercase.
Why? Just cuz, that's why.
Hope it helps.. took me a very long time to figure it out..
Pat NH USA
If you are trying to send the mail from a different server (may be from your localhost) then this error comes, so if you want to test your smtp mail code you need to upload your code to your remote server and test (plesk server in my case) then it will work.
The answer by #puneet that mentions smtp.UseDefaultCredentials = false got us on the right track.
But our case was slightly different. We also got error Bad sequence of commands. The server response was: You must authenticate first (#5.5.1) but it only happened on password resets using the Password Recovery web part built in to ASP.NET Membership.
The Password Recovery web part relies on a web.config section called <mailSettings> so we changed defaultCredentials="true" to defaultCredentials="false" in web.config
<mailSettings>
<smtp deliveryMethod="Network" from="donotreply#someone.net">
<network defaultCredentials="false" host="mail.someone.net" userName="notifier#someone.net" password="password" port="587" />
</smtp>
And this fixed the error with Password Reset. Basically this is the same fix as #puneet but in a different location.
System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient(System.Configuration.ConfigurationSettings.AppSettings["smtp"]);
//code by cv 8july2014
mailClient.UseDefaultCredentials = false; // <<<you need THIS
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = "username";
NetworkCred.Password = "Pasword";
mailClient.Credentials = NetworkCred;
// mailClient.Host = "my company mail site";//host of your mail account
mailClient.Port = 2525;
// mailMsg = null;
//SmtpMail.SmtpServer = System.Configuration.ConfigurationSettings.AppSettings["smtp"];
while (counter < 3)
{
try
{
mailClient.Send(mailMsg);
Thread.Sleep(2000);
counter = 3;
mailMsg = null;
}
catch (Exception ex)
{
counter = counter + 1;
if (counter == 2)
{
throw ex;
counter = 0;
}
}
}