Sending Email in .Net Through Gmail

Sending email in .NET through Gmail

Be sure to use System.Net.Mail, not the deprecated System.Web.Mail. Doing SSL with System.Web.Mail is a gross mess of hacky extensions.

using System.Net;
using System.Net.Mail;

var fromAddress = new MailAddress("from@gmail.com", "From Name");
var toAddress = new MailAddress("to@example.com", "To Name");
const string fromPassword = "fromPassword";
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);
}

Additionally go to the Google Account > Security page and look at the Signing in to Google > 2-Step Verification setting.

  • If it is enabled, then you have to generate a password allowing .NET to bypass the 2-Step Verification. To do this, click on Signing in to Google > App passwords, select app = Mail, and device = Windows Computer, and finally generate the password. Use the generated password in the fromPassword constant instead of your standard Gmail password.
  • If it is disabled, then you have to turn on Less secure app access, which is not recommended! So better enable the 2-Step verification.

C# sending email via Gmail account

If your Gmail account has 2-Step Verification enabled you will have to create an App-Specific Password to authenticate with instead.

Note also that SmtpClient is IDisposable - you should be putting it in a using (var smtpClient = new SmtpClient("smtp.gmail.com", 587)) { ... } block so that the SMTP connection RSETs, QUITs and closes correctly.

== edit ==

Also, it appears you have the from and recipients parameters switched around on smtpClient.Send.

string body = "<head>" +
"Here comes some logo" +
"</head>" +
"<body>" +
"<h1>Account confirmation reqest.</h1>" + Environment.NewLine +
"<a>Dear User, </a>" + Environment.NewLine +
"<a>In order to be able to use musicshop app properly, we require You to confirm Your email address.</a>" + Environment.NewLine +
"<a>This is the last step towards using our app.</a>" + Environment.NewLine +
"<a>Pleas follow this hyperlink to confirm your address.</a>" + Environment.NewLine +
"<a>[Callback url]</a>" +
"</body>";
try
{
using (var smtpClient = new SmtpClient("smtp.gmail.com", 587))
{
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new NetworkCredential()
{
UserName = Config.Username,
Password = Config.Password,
};
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;

//Oops: from/recipients switched around here...
//smtpClient.Send("targetemail@targetdomain.xyz", "myemail@gmail.com", "Account verification", body);
smtpClient.Send("myemail@gmail.com", "targetemail@targetdomain.xyz", "Account verification", body);
}
}
catch (Exception e)
{
Console.Error.WriteLine("{0}: {1}", e.ToString(), e.Message);
}

Sending email through Gmail SMTP server with C#

CVertex, make sure to review your code, and, if that doesn't reveal anything, post it. I was just enabling this on a test ASP.NET site I was working on, and it works.

Actually, at some point I had an issue on my code. I didn't spot it until I had a simpler version on a console program and saw it was working (no change on the Gmail side as you were worried about). The below code works just like the samples you referred to:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net;

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
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");
Console.WriteLine("Sent");
Console.ReadLine();
}
}
}

I also got it working using a combination of web.config, http://msdn.microsoft.com/en-us/library/w355a94k.aspx and code (because there is no matching EnableSsl in the configuration file :( ).

2021 Update

By default you will also need to enable access for "less secure apps" in your gmail settings page: google.com/settings/security/lesssecureapps. This is necessary if you are getting the exception "`The server response was: 5.5.1 Authentication Required. – thanks to @Ravendarksky

Sending Asp.Net email through gmail

You need client.EnableSsl=true;

Check the code from this site: Email via Gmail

Here is an example on how to send HTML email from your ASP.NET page using your Google account.
(This setup can be easily used to send messages via any other SMTP server that requires authentication).
Note: the code snippet assumes you have a Label component on Page with named lblMsg that will show
success/failure message to the user that is sending email.
(But this can be easily changed).

   SmtpClient client = new SmtpClient();
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
client.Host = "smtp.gmail.com";
client.Port = 587;

// setup Smtp authentication
System.Net.NetworkCredential credentials =
new System.Net.NetworkCredential("your_account@gmail.com", "yourpassword");
client.UseDefaultCredentials = false;
client.Credentials = credentials;

MailMessage msg = new MailMessage();
msg.From = new MailAddress("your_account@gmail.com");
msg.To.Add(new MailAddress("destination_address@someserver.com"));

msg.Subject = "This is a test Email subject";
msg.IsBodyHtml = true;
msg.Body = string.Format("<html><head></head><body><b>Test HTML Email</b></body>");

try
{
client.Send(msg);
lblMsg.Text = "Your message has been successfully sent.";
}
catch (Exception ex)
{
lblMsg.ForeColor = Color.Red;
lblMsg.Text = "Error occured while sending your message." + ex.Message;
}

How to send an e-mail with C# through Gmail

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();
}
}

If the above code don't work , try to change it like the following code :

    SmtpClient client = new SmtpClient();
client.Host = "smtp.gmail.com";
client.Port = 587;
client.EnableSsl = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("YourMail@gmail.com", "YourPassword");

Email sending fail using gmail smpt service in .NET Core application

Switch those two lines:

smtp.Credentials = new NetworkCredential(emailFromAddress, password);
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false; //<----

to this:

smtp.UseDefaultCredentials = false; //<----
smtp.Credentials = new NetworkCredential(emailFromAddress, password);
smtp.EnableSsl = true;

It is veeeery good example how to NOT use properties. Setting one resets another. This should probably be a bug, but no one will fix this legacy.

PS this behavior is described in this post - The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required?

How to send email using ASP.NET, C# and GMail

Before calling SmtpClient.Send(), add:

smtp.UseDefaultCredentials = false;

According to the MSDN SmtpClient page, UseDefaultCredentials is set to false by default, but there seems to be a bug somewhere that is setting it to true. Explicitly set it to false before sending the message and it should be all set.



Related Topics



Leave a reply



Submit