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
Related
The code I currently have is:
public void SendEmail(string to, string cc, string bcc, string subject, string body, string attachmentPath = "", System.Net.Mail.MailPriority emailPriority = MailPriority.Normal, BodyType bodyType = BodyType.HTML)
{
try
{
var client = new System.Net.Mail.SmtpClient();
{
client.Host = "smtp-mail.outlook.com";
client.Port = 587;
client.UseDefaultCredentials = false;
client.EnableSsl = true;
client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
client.Credentials = new NetworkCredential("[my company email]", "[my password]");
client.Timeout = 600000;
}
MailMessage mail = new MailMessage("[insert my email here]", to);
mail.Subject = subject;
mail.Body = body;
client.Send(mail);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
The email address I'm trying to send to is hosted on Office 365's Outlook. We might have to change the specific address later, but they'd likely be configured the same.
However, whenever I try to run the client.Send(mail); command, I receive the same error. The full text of the error is:
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM
I've tried a few different things, like switching the port between 25 and 587, changing the host to Office365's, or toggling UseDefaultCredentials and EnableSssl to true or false. But I always see the same error. Is there something else I'm missing?
I found an example code block elsewhere on this site and replacing everything I had with it made the difference.
The function name and parameters were the same, but here's what I replaced the body of it with.
var _mailServer = new SmtpClient();
_mailServer.UseDefaultCredentials = false;
_mailServer.Credentials = new NetworkCredential("my email", "my password");
_mailServer.Host = "smtp.office365.com";
_mailServer.TargetName = "STARTTLS/smtp.office365.com";
_mailServer.Port = 587;
_mailServer.EnableSsl = true;
var eml = new MailMessage();
eml.Sender = new MailAddress("my email");
eml.From = eml.Sender;
eml.To.Add(new MailAddress(to));
eml.Subject = subject;
eml.IsBodyHtml = (bodyType == BodyType.HTML);
eml.Body = body;
_mailServer.Send(eml);
I don't know for certain but I think that replacing the Host value with the smtp Office 365 link rather than an outlook one, as well as remembering to add a Target Name which I did not have before, both did the trick and solved the authorization issue (I had previously confirmed it wasn't a credentials issue with our tech support).
Hello all can anyone please explain what would the UserName and Password be? I believe that those are asking for my gmail's username and password right? (I'm the one who will always receive emails) I am trying to implement the email service for my contact form. Sorry I'm pretty new to asp.net mvc.
public class MailService : IMailService
{
public string SendMail(string from, string to, string subject, string body)
{
var errorMessage = "";
try
{
var msg = new MailMessage(from, to, subject, body);
using (var smtp = new SmtpClient())
{
var credential = new NetworkCredential
{
UserName = "myemail#yahoo.com",
Password = "password"
};
smtp.Credentials = credential;
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.Send(msg);
}
}
catch (Exception ex)
{
errorMessage = ex.Message;
}
return errorMessage;
}
}
Yes. The Username and Password are the ones required by your host. In this case the credentials you need to login at smtp.gmail.com
Yes, you need to authenticate using the login information just as if you were setting up an email client to send emails.
SmtpClient.Credentials Property
Gets or sets the credentials used to authenticate the sender.
....
Some SMTP servers require that the client be authenticated before the server will send e-mail on its behalf.
Yes, it's the gmail username and password.
Remember to create a application specific password and use that instead of the actual gmail password
Found the following code in one of my projects:
static Task sendMail(IdentityMessage message)
{
string text = string.Format("Please confirm your account by pasting this link on your browser\'s address bar:\n\n{0}", message.Body);
string html = "Please confirm your account by clicking this link<br/>";
MailMessage msg = new MailMessage();
msg.From = new MailAddress("id#gmail.com");
msg.To.Add(new MailAddress(message.Destination));
msg.Subject = message.Subject;
msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(text, null, MediaTypeNames.Text.Plain));
msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html));
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", Convert.ToInt32(587));
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("id#gmail.com", "gmailpassword");
smtpClient.Credentials = credentials;
smtpClient.EnableSsl = true;
return smtpClient.SendMailAsync(msg);
}
I am trying the send email code in asp.net mvc but I keep getting the error {"Failure sending mail."} I have referred to many of the questions asked here and tried out the suggested sollutions but still got the same error. Where am I going wrong?
Here is my code:
private static void SendEmailWithErrors(string result)
{
SmtpClient smtpclient = new SmtpClient();
MailMessage message = new MailMessage();
try
{
MailAddress fromAddress = new MailAddress("email address");
smtpclient.Host = "smtp.gmail.com";
smtpclient.Port = 587;
smtpclient.UseDefaultCredentials = true;
smtpclient.EnableSsl = true;
smtpclient.Credentials = new System.Net.NetworkCredential("email address", "password");
message.From = fromAddress;
message.To.Add("email address");
message.Subject = "Exception raised";
message.IsBodyHtml = false;
message.Body = result;
smtpclient.Send(message);
}
catch(Exception ex)
{
}
}
Check in to your Email ID from which you are sending the message from. There is a chance there is a warning mail sent to you that someone is trying to illegally access your mail. Just make sure to lower your security for your email to allow 3rd party apps to access it. In case of Gmail, this is done in privacy settings.
It should work fine once the security of the from email address is lowered.
private static void SendEmail(string result)
{
var fromAddress = new MailAddress("from#gmail.com", "From Name");
var toAddress = new MailAddress("to#example.com", "To Name");
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 = "Mail Subject",
Body = result
})
{
smtp.Send(message);
}
}
Thank you all for posting your answers, I am using the local machine and the IP address is already configured in the server machine, so that was causing the conflict. The code works fine when I run the application from the server machine.
I have been trying for 2 days to get my ASP.NET webforms application to send an e-mail.
I have tried this using both outlook and gmail. I got the smtp information for both from this tutorial:
When I try using port 587 in the example below I get an error saying:
An exception of type 'System.Net.Mail.SmtpException' occurred in System.dll but was not handled in user code
Additional information: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.
When I try using port 465 in the example below:
My application just hangs forever and my page never gets back my email function which is in the PageLoad.
A couple of things to note just incase one of these is messing me up:
I am using a standard VS2013 dev environment (running my web app in debug mode using F5)
I am using the same e-mail address for from, to, and gmail login credentials)
My ISP does not block these ports. (comcast cable)
I even went to the google DisplayUnlockCaptcha page to Allow access to my account
protected void SendEmail()
{
string EmailAddress = "myemail#gmail.com";
using (MailMessage mailMessage = new MailMessage(EmailAddress, EmailAddress))
{
mailMessage.Subject = "This is a test email";
mailMessage.Body = "This is a test email. Please reply if you receive it.";
SmtpClient smtpClient = new SmtpClient();
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587;
smtpClient.Credentials = new System.Net.NetworkCredential()
{
UserName = EmailAddress,
Password = "password"
};
smtpClient.UseDefaultCredentials = false;
smtpClient.Send(mailMessage);
}
}
This code should work fine for you
protected void SendEmail()
{
string EmailAddress = "myemail#gmail.com";
MailMessage mailMessage = new MailMessage(EmailAddress, EmailAddress);
mailMessage.Subject = "This is a test email";
mailMessage.Body = "This is a test email. Please reply if you receive it.";
SmtpClient smtpClient = new SmtpClient();
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587;
smtpClient.Credentials = new System.Net.NetworkCredential()
{
UserName = EmailAddress,
Password = "password"
};
smtpClient.UseDefaultCredentials = false;
smtpClient.Send(mailMessage);
}
You'll need to set the delivery mode otherwise gmail will return an error
EDIT:
Throwing an 'using' around 'MailMessage' might also be a smart thing to do
It turns out that it is because of a GMail security setting.
https://www.google.com/settings/security/lesssecureapps
You have to enable access for less secure apps.
public void sendEmail(string body)
{
if (String.IsNullOrEmpty(email))
return;
try
{
MailMessage mail = new MailMessage();
mail.To.Add(email);
mail.To.Add("xxx#gmail.com");
mail.From = new MailAddress("yyy#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
("yyy#gmail.com", "pw"); // ***use valid credentials***
smtp.Port = 587;
//Or your Smtp Email ID and Password
smtp.EnableSsl = true;
smtp.Send(mail);
}
catch (Exception ex)
{
print("Exception in sendEmail:" + ex.Message);
}
}``
http://www.c-sharpcorner.com/UploadFile/47548d/how-to-send-bulk-email-using-Asp-Net/
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Sending email in .NET through Gmail
This mail code is working in localhost i.e on my computer but when i uopload it on server it is not working.
The error is : Failure sending mail. please tell me where is the problem.
if (Session["userinfo"] != null)
{
lblTest.Text = Session["userinfo"].ToString();
MailMessage msg = new MailMessage();
msg.From = new MailAddress("shop.bcharya#gmail.com");
msg.To.Add(new MailAddress("bcc#dr.com"));
msg.To.Add(new MailAddress("info#yzentech.com"));
msg.Subject = "Mail from BcharyaCorporation.online shopping site";
msg.Body = ""+lblTest.Text+" wants to buy some products. please contact with him/her";
SmtpClient sc = new SmtpClient();
sc.Host = "smtp.gmail.com";
// sc.Port = 25;
sc.Credentials = new NetworkCredential("shop.bcharya#gmail.com", "mypassword");
sc.EnableSsl = true;
try
{
sc.Send(msg);
lblPayment.Text = "Sorry. Currently we are out of online payment service. We will contact you for payment process. Thank you for buying this product.";
}
catch (Exception ex)
{
lblPayment.Text=ex.Message.ToString();
Response.Write(ex.Message);
}
}
For gmail mail settings add Port number too
sc.Port = 587;
after this line
sc.Host = "smtp.gmail.com";
Only use port 587 and SSL if the SMTP server supports that (GMail and Hotmail for example). Some servers just use port 25 and no SSL.
Use below method and then check :
SmtpClient sc = new SmtpClient(string); //sends e-mail by using the specified SMTP server
You can use this below given code for sending email. Here sending the error details through email is one method. Try this code for sending email.
using System.Web.Mail
public static bool SendErrorEmail(string to, string cc, string bcc, string subject, string body, MailPriority priority, bool isHtml)
{
try
{
using (SmtpClient smtpClient = new SmtpClient())
{
using (MailMessage message = new MailMessage())
{
MailAddress fromAddress = new MailAddress(“yourmail#domain.com”, “Your name”);
// You can specify the host name or ipaddress of your server
smtpClient.Host = “mail.yourdomain.com”; //you can specify mail server IP address here
//Default port is 25
smtpClient.Port = 25;
NetworkCredential info = new NetworkCredential(“yourmail#domain.com”, “your password”);
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = info;
//From address will be given as a MailAddress Object
message.From = from;
message.Priority = priority;
// To address collection of MailAddress
message.To.Add(to);
message.Subject = subject;
// CC and BCC optional
if (cc.Length > 0)
{
message.CC.Add(cc);
}
if (bcc.Length > 0)
{
message.Bcc.Add(bcc);
}
//Body can be Html or text format;Specify true if it is html message
message.IsBodyHtml = isHtml;
// Message body content
message.Body = body;
// Send SMTP mail
smtpClient.Send(message);
}
}
return true;
}
catch (Exception ee)
{
Logger.LogError(ee, “Error while sending email to ” + toAddress);
throw;
}
}