How to send mail gmail via smtp? - c#

I'm receiving an exception when trying to execute this mail-sending method.
{"Syntax error, command unrecognized. The server response was: "}
my code:
public async static Task SendExceptionMail(Exception e)
{
try
{
//TODO: fill..
var message = new MailMessage();
message.To.Add("other_email_than_my_email#gmail.com");
message.From = new MailAddress("my_email_in_gmail#gmail.com");
message.Subject = "Server Exception Occured";
StringBuilder sb = new StringBuilder();
sb.AppendLine("Exception occured. Stack trace:");
sb.AppendLine(e.StackTrace);
sb.AppendLine("");
sb.AppendLine("Time: " + DateTime.UtcNow);
message.Body = sb.ToString();
message.IsBodyHtml = false;
message.BodyEncoding = UTF8Encoding.UTF8;
using (var smtpClient = new SmtpClient())
{
smtpClient.Credentials = new System.Net.NetworkCredential("my_email_in_gmail#gmail.com", "very_very_complicated_password_with_numbers_and_signs");
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 465;
smtpClient.EnableSsl = true;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
//smtpClient.UseDefaultCredentials = false;
await smtpClient.SendMailAsync(message);
}
}
catch (Exception ex)
{
Console.Write(ex.StackTrace);
}
}
In my Gmail account, I allowed IMAP and POP in the settings tab.
What I've tried:
Changing the port to 587 and 25. this time I'm getting The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at
commenting/uncommenting the UseDefaultCredentials line, the DeliveryMethod properties
commenting/uncommenting the IsBodyHtml and BodyEncoding properties

I suggest you to follow this - Sending email in .NET through Gmail and Cannot send mail from certain server
-First Check whether "Allowing less secure apps to access your account" is enable in google account setting then check with below code:
using (var smtpClient = new SmtpClient())
{
smtpClient.Credentials = new System.Net.NetworkCredential("my_email_in_gmail#gmail.com", "very_very_complicated_password_with_numbers_and_signs");
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587; // Google smtp port
smtpClient.EnableSsl = true;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.UseDefaultCredentials = false;// disable it
/// Now specify the credentials
smtpClient.Credentials = new NetworkCredential(message.From.Address, fromPassword)
await smtpClient.SendMailAsync(message);
}
There may be some firewall issue .
References:
SendEmail in ASP.net shows me Syntax error, command unrecognized. The server response was: Dovecot ready
Syntax error, command unrecognized. The server response was ''
Hope this help.

Related

ASP.NET C# - Sending Email from Gmail/Yahoo Live SMTP Server not working

I am struggling with attempting to send email from a .NET application.
I have tried everything from making a new account both gmail and yahoo (changed the host for yahoo), as well as, changing the port using and not using mail.To, allowing less secure apps, i also tried enabling 2 step verification and giving an application password for gmail all of which have failed with the same caught error of: {"The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.1 Authentication required"}
This is my code:
SmtpClient smtpClient = new SmtpClient();
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("myemail#gmail.com", "pw");
smtpClient.Credentials = credentials;
smtpClient.UseDefaultCredentials = false;
smtpClient.Port = 587;
smtpClient.EnableSsl = true;
smtpClient.Host = "smtp.gmail.com";
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
MailMessage mail = new MailMessage();
mail.From = new MailAddress("myemail#gmail.com");
mail.To.Add("myemail#gmail.com");
mail.IsBodyHtml = true;
mail.Subject = txtSubject.Text;
mail.Body = txtBody.Text;
try
{
smtpClient.Send(mail);
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (mail != null)
{
mail.Dispose();
}
}
Solution: as people may have the problem in the future the solution was to remove the line of code: smtpClient.UseDefaultCredentials = false;
smtpClient.UseDefaultCredentials = false;
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("myemail#gmail.com", "pw");
smtpClient.Credentials = credentials;
Use those lines in such order.

smtp exception “failure sending mail”

I created console application for sending Email
public static void sendEmail(string email, string body)
{
if (String.IsNullOrEmpty(email))
return;
try
{
MailMessage mail = new MailMessage();
mail.To.Add(email);
mail.From = new MailAddress("test#gmail.com");
mail.Subject = "sub";
mail.Body = body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
smtp.Credentials = new System.Net.NetworkCredential("test#gmail.com", "admin#1234"); // ***use valid credentials***
smtp.Port = 587;
//Or your Smtp Email ID and Password
smtp.EnableSsl = true;
smtp.Send(mail);
}
catch (Exception ex)
{
}
}
I am using correct credential of my gmail account.
Is there any settings I need to do for GMail Account?
It's likely that you're actually getting this error, it's just suppressed in some way by you being in a console app.
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.
Change this piece of code and add one extra line. It's important that it goes before the credentials.
smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
// ** HERE! **
smtp.UseDefaultCredentials = false;
// ***********
smtp.Credentials = new System.Net.NetworkCredential("test#gmail.com", "admin#1234"); // ***use valid credentials***
smtp.Port = 587;
You'll also need to go here and enable less secure apps.
https://www.google.com/settings/security/lesssecureapps
Or if you have two step authentication on your account you'll need to set an app specific password, then use that password in your code instead of your main account password.
I've just tested and verified this works on my two step account. Hell, here's my entire method copied right out of LINQPad in case it helps (with removed details of course).
var fromAddress = new MailAddress("myaccount#gmail.com", "My Name");
var toAddress = new MailAddress("test.address#email.com", "Mr Test");
const string fromPassword = "tbhagpfpcxwhkczd";
const string subject = "test";
const string body = "HEY, LISTEN!";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
Timeout = 20000
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
Edit:
Using attachments:
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
Attachment attachment = new Attachment(filePath);
message.Attachments.Add(attachment);
smtp.Send(message);
}
In my experienced using C# SMTP Client, there is a certain steps to follow in the code (see code snippet below)
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587;
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.Credentials = new NetworkCredential("account#gmail.com", "secretPassword");
smtpClient.Send(mail);

Send email in C# namecheap private email

I setup a private email with my namecheap domain but I am having trouble sending e-mails. Below is my code. Am I missing anything? I get a timeout message each time.
//Send email to end user
MailMessage mm = new MailMessage();
foreach(string to in toList)
{
mm.To.Add(to);
}
mm.From = new System.Net.Mail.MailAddress("fromaddress");
mm.Subject = subject;
mm.Body = body;
mm.IsBodyHtml = true;
var smtp = new SmtpClient
{
Host = "mail.privateemail.com",
Port = 465,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential("username", "pw"),
Timeout = 20000
};
smtp.Send(mm);
Port number may be wrong. I tried with 587 and it worked on gmail.
And consider to remove timeout temporarily to get an exception and find out the detailed reason of the timeout.
The solution is:
Host: smtp.privateemail.com
Port: 587
EnableSsl: true;
SecurityProtocol: (SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12);
This code is what I've used with success.
string to = "yo#yo.com";
string from = "help#help.com";
MailMessage message = new MailMessage(from, to);
message.Subject = "Using the new SMTP client.";
message.Body = #"Using this new feature, you can send an e-mail message from an application very easily.";
SmtpClient client = new SmtpClient("mail.privateemail.com");
client.Credentials = new System.Net.NetworkCredential("username", "pass");
client.Port = 587;
client.EnableSsl = true;
try
{
client.Send(message);
}
catch (Exception ex)
{
Console.WriteLine("Error: {0}",
ex.ToString());
}
Namecheap now only supports SMTP on port 465 and implicit SSL after their most recent udpate. System.Net.Mail unfortunately does not support this (see here). A work around could be to use the System.Web.Mail namespace (just a heads up it is obsolete) however it does work as seen in this SO post.

How to fix the smtp authentication runtime error when sending email using smtp client?

I'm sending simple email messages in my application using smtp client and I was using this code before and it just works fine. Now, when I tried to run my project again from my local host computer and try to send email messages. I got a runtime error that says
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.
I don't know what just happened since it was working fine before. Now I can't send email and all I've got is this error. I could hardly troubleshoot what went wrong. How do I resolve this? Here's my code below: Thanks...
SmtpClient client = new SmtpClient();
client.Host = "smtp.gmail.com";
client.Port = 587;
client.EnableSsl = true;
client.Credentials = new System.Net.NetworkCredential(#"myemailaddress#gmail.com",#"myemailpassword");
// create message
MailMessage message = new MailMessage();
message.From = new MailAddress(TextBox4.Text);
message.To.Add(new MailAddress(TextBox1.Text));
message.Subject = TextBox2.Text;
message.Body = TextBox3.Text; //body of the message to be sent
message.BodyEncoding = System.Text.Encoding.UTF8;
message.IsBodyHtml = true;
// message.Subject = "subject";
message.SubjectEncoding = System.Text.Encoding.UTF8;
try
{
client.Send(message);
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Alert", "alert('Mail has been successfully sent!')", true);
}
catch (SmtpException ex)
{
Response.Write(ex.Message);
}
finally
{
// Clean up.
message.Dispose();
}
Just Go here : Less secure apps , Log on using your Email and Password which use for sending mail in your c# code , and choose Turn On.
Also please go to this link and click on Continue Allow access to your Google account
also I edit it little bit :
public string sendit(string ReciverMail)
{
MailMessage msg = new MailMessage();
msg.From = new MailAddress("YourMail#gmail.com");
msg.To.Add(ReciverMail);
msg.Subject = "Hello world! " + DateTime.Now.ToString();
msg.Body = "hi to you ... :)";
SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = true;
client.Host = "smtp.gmail.com";
client.Port = 587;
client.EnableSsl = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Credentials = new NetworkCredential("YourMail#gmail.com", "YourPassword");
client.Timeout = 20000;
try
{
client.Send(msg);
return "Mail has been successfully sent!";
}
catch (Exception ex)
{
return "Fail Has error" + ex.Message;
}
finally
{
msg.Dispose();
}
}

Gmail: How to send an email programmatically

Possible Exact Duplicate: Sending Email in C#.NET Through Gmail
Hi,
I'm trying to send an email using gmail:
I tried various examples that I found on this site and other sites but I always get the same error:
Unable to connect to the remote server -- > System.net.Sockets.SocketException: No connection could be made because the target actively refused it 209.85.147.109:587
public static void Attempt1()
{
var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("MyEmailAddress#gmail.com", "MyPassWord"),
EnableSsl = true
};
client.Send("MyEmailAddress#gmail.com", "some.email#some.com", "test", "testbody");
}
Any ideas?
UPDATE
More details.
Maybe I should say what other attempts I made that gave me the same error:
(Note when i didn't specify a port it tryed port 25)
public static void Attempt2()
{
var fromAddress = new MailAddress("MyEmailAddy#gmail.com", "From Name");
var toAddress = new MailAddress("MyEmailAddy#dfdf.com", "To Name");
const string fromPassword = "pass";
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); }
}
public static void Attempt3()
{
MailMessage mail = new MailMessage();
mail.To.Add("MyEmailAddy#dfdf.com");
mail.From = new MailAddress("MyEmailAddy#gmail.com");
mail.Subject = "Email using Gmail";
string Body = "Hi, this mail is to test sending mail" +
"using Gmail in ASP.NET";
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Credentials = new System.Net.NetworkCredential
("MyEmailAddy#gmail.com", "pass");
smtp.EnableSsl = true;
smtp.Send(mail);
}
I'm using the following code:
SmtpClient sc = new SmtpClient("smtp.gmail.com");
NetworkCredential nc = new NetworkCredential("username", "password");//username doesn't include #gmail.com
sc.UseDefaultCredentials = false;
sc.Credentials = nc;
sc.EnableSsl = true;
sc.Port = 587;
try {
sc.Send(mm);
} catch (Exception ex) {
EventLog.WriteEntry("Error Sending", EventLogEntryType.Error);
}
With the following code, it will work successfully.
MailMessage mail = new MailMessage();
mail.From = new MailAddress("abc#mydomain.com", "Enquiry");
mail.To.Add("abcdef#yahoo.com");
mail.IsBodyHtml = true;
mail.Subject = "Registration";
mail.Body = "Some Text";
mail.Priority = MailPriority.High;
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
//smtp.UseDefaultCredentials = true;
smtp.Credentials = new System.Net.NetworkCredential("xyz#gmail.com", "<my gmail pwd>");
smtp.EnableSsl = true;
//smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Send(mail);
But, there is a problem with using gmail. The email will be sent successfully, but the recipient inbox will have the gmail address in the 'from address' instead of the 'from address' mentioned in the code.
To solve this, please follow the steps mentioned at the following link.
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
Here is my connection resource to connect to Gmail from Java
<!-- Java Mail -->
<Resource name="mail/MailSession" auth="Container" type="javax.mail.Session"
mail.debug="true"
mail.transport.protocol="smtp"
mail.smtp.host="smtp.gmail.com"
mail.smtp.user="youremail#gmail.com"
mail.smtp.password="yourpassword"
mail.smtp.port="465"
mail.smtp.starttls.enable="true"
mail.smtp.auth="true"
mail.smtp.socketFactory.port="465"
mail.smtp.socketFactory.class="javax.net.ssl.SSLSocketFactory"
mail.smtp.socketFactory.fallback="false"
mail.store.protocol="pop3"
mail.pop3.host="pop.gmail.com"
mail.pop3.port="995" />
Connect your Gmail account on Secure ports (465 for SMTP and 995 for POP3) and use any .NET SSL Factory available to connect securely to Gmail.
Are you sure that your GMail account is set up to allow POP/SMTP connections? It is a configurable option that you can turn on and off as you choose.
You can see my blog post here at http://codersatwork.wordpress.com/2010/02/14/sending-email-using-gmail-smtp-server-and-spring-mail/ which explains how to use spring mail for sending email via gmail smtp server.
I used java but you can see the configuration and use that in your c# code.
Try using port number 465 for SSL connection

Categories