Sending Email Through Gmail Smtp Server With C#

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

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

How to send email via SMTP from my corporate gmail address using C#

I just tested with your code on my company G-Suite account.

After allowing users to manage their own settings, you need to make sure that the username provided in the NetworkCredential object has been configured to "Allow less secure apps". You can get to it by:

  1. Enable users to manage their own settings (you've already done this)
  2. Going to (in this case) to the Google Account Page for info@mydomain.com.
  3. Clicking "Sign In and Security"
  4. Scroll to the bottom and make sure the slider is on.

The first step may take some time to propagate to all users in G-Suite.

Note: You will also get this error if the password or username are incorrect.

If you've done all of the above and it still doesn't work, you may need to configure SPF in your DNS settings. See Authorize email senders with SPF.

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");

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.

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?

sending email from smtp gmail in c#

Its a security issue, Gmail by default prevents access for your mail account from custom applications. You can set it up to accept the login from your application.
Sample Image
After Logging in to your mail ,

https://www.google.com/settings/security/lesssecureapps

Update:

 msg.IsBodyHtml = true;


Related Topics



Leave a reply



Submit