Does .NET 4 has any problems in sending emails? I had a .NET 3.5 solution and it was working then migrated the solution to .NET 4 and It does not works; nothing changed!
Notes:
I get this exception:
System.Net.Mail.SmtpException: 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
at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response)
at System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, String from)
at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, SmtpFailedRecipientException& exception)
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at ...
And this is my code:
public static void SendEmail(
this Email email)
{
if (email.MailingSettings == null) throw new ArgumentNullException("email.MailingSettings", "specify email.MailingSettings");
var settings = email.MailingSettings;
if (string.IsNullOrEmpty(email.Sender)) throw new ArgumentException("email.Sender", "specify a sender");
if (email.Recipients == null) throw new ArgumentNullException("email.Recipients", "specify at least a recipient");
if (email.Recipients.Length == 0) throw new ArgumentNullException("email.Recipients", "specify at least a recipient");
if (string.IsNullOrEmpty(settings.SMTPHost)) throw new ArgumentException("email.SMTPHost", "specify email.SMTPHost");
var mail = new MailMessage();
if (string.IsNullOrEmpty(email.SenderDisplayName))
mail.From = new MailAddress(email.Sender);
else
mail.From = new MailAddress(email.Sender, email.SenderDisplayName);
if (!string.IsNullOrEmpty(email.ReplyTo))
{
if (string.IsNullOrEmpty(email.ReplyToDisplayName))
{
mail.ReplyToList.Add(new MailAddress(email.ReplyTo));
}
else
{
mail.ReplyToList.Add(new MailAddress(email.ReplyTo, email.ReplyToDisplayName));
}
}
foreach (string recipient in email.Recipients)
mail.To.Add(new MailAddress(recipient));
mail.Subject = email.Subject;
mail.Body = email.Body;
mail.IsBodyHtml = settings.IsBodyHtml;
if (email.CC != null && email.CC.Length > 0)
foreach (string cci in email.CC)
mail.CC.Add(cci);
if (email.BCC != null && email.BCC.Length > 0)
foreach (string bcci in email.BCC)
mail.Bcc.Add(bcci);
if (email.Attachments != null)
foreach (var ifn in email.Attachments)
mail.Attachments.Add(
new Attachment(
new MemoryStream(
ifn.Content),
ifn.FileName));
var smtpPort = settings.SMTPPort > 0 ? settings.SMTPPort : 25;
var smtpClient = new SmtpClient(settings.SMTPHost, smtpPort);
smtpClient.EnableSsl = settings.EnableSsl;
if (!string.IsNullOrEmpty(settings.SMTPUser))
{
smtpClient.UseDefaultCredentials = false;
var smtpPassword = settings.SMTPPassword == null ? string.Empty : settings.SMTPPassword;
NetworkCredential netCred;
if (string.IsNullOrEmpty(settings.SMTPDomain))
netCred = new NetworkCredential(settings.SMTPUser, smtpPassword);
else
netCred = new NetworkCredential(settings.SMTPUser, smtpPassword, settings.SMTPDomain);
smtpClient.Credentials = netCred;
}
else
smtpClient.Credentials = CredentialCache.DefaultNetworkCredentials;
smtpClient.Timeout = 180 * 1000;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
ServicePointManager.ServerCertificateValidationCallback =
delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{ return true; };
smtpClient.Send(mail);
}
If everything is as per posted-code and comments then I can say that you've turned on 2-step verification of your google account and in that case you need to generate Application Specific-password.
This code is correct and works. The problem was on GMail side and solved (not detected why and how).
Try to use this :
try
{
string smtpAddress = "smtp.gmail.com";
int portNumber = 587;
bool enableSSL = true;
string emailFrom = "senderemail#gmail.com";
string password = "password";
string emailTo = "receiver#gmail.com";
string subject = "Halo!";
string body = "Halo, Mr. SMTP";
MailMessage mail = new MailMessage();
mail.From = new MailAddress(emailFrom);
mail.To.Add(emailTo);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
{
smtp.Credentials = new NetworkCredential(emailFrom, password);
smtp.EnableSsl = enableSSL;
smtp.Send(mail);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
*Note before that you need to activated this : https://myaccount.google.com/lesssecureapps
and then build and run the code.. it's amazing.. :)
Related
using System.Net.Mail;
protected void SendMail()
{
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.google.com");
SmtpServer.Timeout = 30000;
SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
mail.From = new MailAddress("myemail#gmail.com");
mail.To.Add("recipient#gmail.com");
mail.Subject = "test";
mail.Body = "test";
mail.Priority = MailPriority.High;
SmtpServer.Port = 587;//25
SmtpServer.Credentials = new System.Net.NetworkCredential("myemail#gmail.com", "pwd");
SmtpServer.EnableSsl = true;
SmtpServer.UseDefaultCredentials = false;
SmtpServer.Send(mail);
//MessageBox.Show("mail Send");
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message.ToString());
}
}
I have not found any error in my code as per several sources on internet. Still this is not working out.
Change you gmail Account Access
Sign in with your Google Account and redirect to this link
https://www.google.com/settings/security/lesssecureapps
Press the Enable, and try your code again
https://support.google.com/accounts/answer/6010255
Try this method
In Gmail Use Port-25 and SMTP-smtp.gmail.com
public void mail(string FromEmail, string FromPass, string To, string Tocc, string Tobcc, string subject, string message, string smtpadd, int portnum)
{
try
{
System.Net.Mail.SmtpClient st = new System.Net.Mail.SmtpClient(smtpadd);
System.Net.Mail.MailMessage mst = new System.Net.Mail.MailMessage();
mst.To.Add(To);
if (Tocc != "")
{
mst.CC.Add(Tocc);
}
if (Tobcc != "")
{
mst.Bcc.Add(Tobcc);
}
mst.IsBodyHtml = true;
mst.From = new System.Net.Mail.MailAddress(FromEmail);
mst.Subject = subject;
mst.Body = message;
System.Net.NetworkCredential nc = new System.Net.NetworkCredential(FromEmail, FromPass);
st.UseDefaultCredentials = true;
st.EnableSsl = true;
st.Port = portnum;
st.Credentials = nc;
st.Send(mst);
}
catch (Exception e)
{
}
}
email fail to send when adding attachment, else it's successful
protected void Button1_Click(object sender, EventArgs e)
{
string temp = Session["captcha"].ToString();
if (temp == txtCaptcha.Text)
{
var mail = new System.Net.Mail.MailMessage();
mail.To.Add(#"my mail");
mail.From = new MailAddress("another email", "it's name",
System.Text.Encoding.UTF8);
mail.Subject = "my subject";
mail.SubjectEncoding = System.Text.Encoding.UTF8;
mail.Body = this.txtDescription.Text.Replace("\n", "<br>");
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.IsBodyHtml = true;
mail.Priority = System.Net.Mail.MailPriority.High;
var client = new SmtpClient();
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("mail", "password");
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
try
{
if (this.fiUpload1.HasFile)
{
this.fiUpload1.SaveAs(Server.MapPath("MyAttach/" + fiUpload1.FileName));
mail.Attachments.Add(new System.Net.Mail.Attachment(Server.MapPath("MyAttach/" + fiUpload1.FileName)));
}
client.Send(mail);
Page.RegisterStartupScript("UserMsg", "<script>alert('Successfully Send...');</script>");
}
catch (Exception ex)
{
Exception ex2 = ex;
string errorMessage = string.Empty;
while (ex2 != null)
{
errorMessage += ex2.ToString();
ex2 = ex2.InnerException;
}
Page.RegisterStartupScript("UserMsg", "<script>alert('Sending Failed...');</script>");
}
}
else
{
Response.Write("Invalid Captcha, try again");
FillCapctha();
}
}
so what am i doing wrong, also should i save the files to my server first or could i just attach it from the client's ?
thanks and have a wonderful day
i've tried to send email using this code..but an error occurred in smtp.Send(mail); messaging "Failure sending mail"
MailMessage mail = new MailMessage();
// set the addresses
mail.From = new MailAddress("from#gmail.com");
mail.To.Add(new MailAddress("to#yahoo.com"));
// set the content
mail.Subject = "test sample";
mail.Body = #"thank you";
SmtpClient smtp = new SmtpClient("smtp.gmail.com");
smtp.Credentials = new NetworkCredential("from#gmail.com", "password");
smtp.Send(mail);
In your code specify port number:
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587)
Also check out this thread Sending email through Gmail SMTP server with C#
You need to set smtp.EnableSsl = true for gmail.
Take a look at this class, it should work for you:
public class Email
{
NetworkCredential credentials;
MailAddress sender;
public Email(NetworkCredential credentials, MailAddress sender)
{
this.credentials = credentials;
this.sender = sender;
}
public bool EnableSsl
{
get { return _EnableSsl; }
set { _EnableSsl = value; }
}
bool _EnableSsl = true;
public string Host
{
get { return _Host; }
set { _Host = value; }
}
string _Host = "smtp.gmail.com";
public int Port
{
get { return _Port; }
set { _Port = value; }
}
int _Port = 587;
public void Send(MailAddress recipient, string subject, string body, Action<MailMessage> action, params FileInfo[] attachments)
{
SmtpClient smtpClient = new SmtpClient();
// setup up the host, increase the timeout to 5 minutes
smtpClient.Host = Host;
smtpClient.Port = Port;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = credentials;
smtpClient.Timeout = (60 * 5 * 1000);
smtpClient.EnableSsl = EnableSsl;
using (var message = new MailMessage(sender, recipient)
{
Subject = subject,
Body = body
})
{
foreach (var file in attachments)
if (file.Exists)
message.Attachments.Add(new Attachment(file.FullName));
if(null != action)
action(message);
smtpClient.Send(message);
}
}
}
fill
mail.Host
and
mail.Port
Properties with proper values
You should be using the using statement when creating a new MailMessage, plus a few things you missed out like port number and enableSSL
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress("from#gmail.com");
mail.To.Add(new MailAddress("to#yahoo.com"));
mail.Subject = "test sample";
mail.Body = #"thank you";
SmtpClient smtpServer = new SmtpClient("smtp.gmail.com");
smtpServer.Port = 587;
smtpServer.Credentials = new NetworkCredential("from#gmail.com", "password");
smtpServer.EnableSsl = true;
smtpServer.Send(mail);
}
Here's a basic GMAIL smtp email implementation I wrote a while ago:
public static bool SendGmail(string subject, string content, string[] recipients, string from)
{
bool success = recipients != null && recipients.Length > 0;
if (success)
{
SmtpClient gmailClient = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
UseDefaultCredentials = false,
Credentials = new System.Net.NetworkCredential("******", "*****") //you need to add some valid gmail account credentials to authenticate with gmails SMTP server.
};
using (MailMessage gMessage = new MailMessage(from, recipients[0], subject, content))
{
for (int i = 1; i < recipients.Length; i++)
gMessage.To.Add(recipients[i]);
try
{
gmailClient.Send(gMessage);
success = true;
}
catch (Exception) { success = false; }
}
}
return success;
}
It should work fine for you, but you'll need to add a valid gmail acocunt where I've marked in the code.
This is the function which i checked to send mail...and it's working properly.
`
private static bool testsendemail(MailMessage message)
{
try
{
MailMessage message1 = new MailMessage();
SmtpClient smtpClient = new SmtpClient();
string msg = string.Empty;
MailAddress fromAddress = new MailAddress("FromMail#Test.com");
message1.From = fromAddress;
message1.To.Add("ToMail#Test1.com");
message1.Subject = "This is Test mail";
message1.IsBodyHtml = true;
message1.Body ="You can write your body here"+message;
smtpClient.Host = "smtp.mail.yahoo.com"; // We use yahoo as our smtp client
smtpClient.Port = 587;
smtpClient.EnableSsl = false;
smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = new System.Net.NetworkCredential("SenderMail#yahoo.com", "YourPassword");
smtpClient.Send(message1);
}
catch
{
return false;
}
return true;
}`
Thank You.
Following is the C# code for Gmail Service
using System;
using System.Net;
using System.Net.Mail;
namespace EmailApp
{
internal class Program
{
public static void Main(string[] args)
{
String SendMailFrom = "Sender Email";
String SendMailTo = "Reciever Email";
String SendMailSubject = "Email Subject";
String SendMailBody = "Email Body";
try
{
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com",587);
SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
MailMessage email = new MailMessage();
// START
email.From = new MailAddress(SendMailFrom);
email.To.Add(SendMailTo);
email.CC.Add(SendMailFrom);
email.Subject = SendMailSubject;
email.Body = SendMailBody;
//END
SmtpServer.Timeout = 5000;
SmtpServer.EnableSsl = true;
SmtpServer.UseDefaultCredentials = false;
SmtpServer.Credentials = new NetworkCredential(SendMailFrom, "Google App Password");
SmtpServer.Send(email);
Console.WriteLine("Email Successfully Sent");
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadKey();
}
}
}
}
For reference: https://www.techaeblogs.live/2022/06/how-to-send-email-using-gmail.html
public static bool SendMail(string toList, string from, string ccList, string subject, string body)
{
MailMessage message = new MailMessage();
SmtpClient smtpClient = new SmtpClient();
try
{
MailAddress fromAddress = new MailAddress(from);
message.From = fromAddress;
message.To.Add(toList);
if (ccList != null && ccList != string.Empty)
message.CC.Add(ccList);
message.Subject = subject;
message.IsBodyHtml = true;
message.Body = body;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
smtpClient.Timeout = 30000;
smtpClient.Host = "smtp.gmail.com"; // We use gmail as our smtp client
smtpClient.Port = 587;
smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = new System.Net.NetworkCredential("myemail#gmail.com", "mypassword");
smtpClient.Send(message);
return true;
}
catch (Exception ex)
{
return false;
}
}
The code seems ok, but still not working, I am not able to figure out why?
any other way to use gmail's smtp to send mail.
try
var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("myusername#gmail.com", "mypwd"),
EnableSsl = true
};
client.Send("myusername#gmail.com", "myusername#gmail.com", "test", "testbody");
If the UseDefaultCredentials property is set to false, then the value set in the Credentials property will be used for the credentials when connecting to the server. Here you set UseDefaultCredentials as true then it will neglect credentials you given.
Please try with Port 25. It's working for me. Also remove setting of UseDefaultCredentials.
Update : Port 587 also working for me. So I think UseDefaultCredentials is only problem in your code. it should be set to false.
public static void SendMail(string ToMail, string FromMail, string Cc, string Body, string Subject)
{
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 25);
MailMessage mailmsg = new MailMessage();
smtp.EnableSsl = true;
smtp.Credentials = new NetworkCredential("email","password");
mailmsg.From = new MailAddress(FromMail);
mailmsg.To.Add(ToMail);
if (Cc != "")
{
mailmsg.CC.Add(Cc);
}
mailmsg.Body = Body;
mailmsg.Subject = Subject;
mailmsg.IsBodyHtml = true;
mailmsg.Priority = MailPriority.High;
try
{
smtp.Timeout = 500000;
smtp.Send(mailmsg);
mailmsg.Dispose();
}
catch (Exception ex)
{
throw ex;
}
}
I can't send a email message using gmail settings. i already tried client.Host ="localhost" it's working but not in client.Host ="smtp.gmail.com".. Please help me guys.. I need use client.Host ="smtp.gmail.com".. thanks
here's my C# code:
string from = "aevalencia119#gmail.com"; //Replace this with your own correct Gmail Address
string to = "aevalencia191#gmail.com"; //Replace this with the Email Address to whom you want to send the mail
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
mail.To.Add(to); mail.From = new
MailAddress(from, "One Ghost" ,System.Text.Encoding.UTF8);
mail.Subject = "This is a test mail" ;
mail.SubjectEncoding = System.Text.Encoding.UTF8; mail.Body = "This is Email Body Text";
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.IsBodyHtml = true ; mail.Priority = MailPriority.High;
SmtpClient client = new SmtpClient(); //Add the Creddentials- use your own email id and password
client.Credentials = new System.Net.NetworkCredential(from, "iseedeadpoeple");
client.Port = 587; // Gmail works on this port client.Host ="smtp.gmail.com";
client.EnableSsl = true; //Gmail works on Server Secured Layer
try
{
client.Send(mail);
}
catch (Exception ex)
{
Exception ex2 = ex;
string errorMessage = string.Empty;
while (ex2 != null)
{
errorMessage += ex2.ToString();
ex2 = ex2.InnerException;
} HttpContext.Current.Response.Write(errorMessage
);
} // end try
here's the error:
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.
Much thanks guys!
You need to get and send mail to GMail by using SSL secutiry certificate
MailMessage msgMail = new MailMessage("a#gmail.com", "b#mail.me", "subject", "message body");
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Credentials = new System.Net.NetworkCredential("a#gmail.com", "a");
try
{
smtp.Send(msgMail);
}
catch (Exception ex)
{
}
reference: http://social.msdn.microsoft.com/Forums/en/netfxnetcom/thread/28b5a576-0da2-42c9-8de3-f2bd1f30ded4
public static string sendMail(string to, string title, string subject, string body)
{
try
{
MailMessage mail = new MailMessage();
SmtpClient smtp = new SmtpClient();
if (to == "")
to = "aevalencia119#gmail.com";
MailAddressCollection m = new MailAddressCollection();
m.Add(to);
mail.Subject = subject;
mail.From = new MailAddress( "aevalencia119#gmail.com");
mail.Body = body;
mail.IsBodyHtml = true;
mail.ReplyTo = new MailAddress("aevalencia119#gmail.com");
mail.To.Add(m[0]);
smtp.Host = "smtp.gmail.com";
client.Port = 587;
smtp.EnableSsl = true;
smtp.Credentials = new System.Net.NetworkCredential("aevalencia119#gmail.com", "####");
ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
smtp.Send(mail);
return "done";
}
catch (Exception ex)
{
return ex.Message;
}
}