911

Instead of relying on my host to send an email, I was thinking of sending the email messages using my Gmail account. The emails are personalized emails to the bands I play on my show.

Is it possible to do it?

Arsen Khachaturyan
  • 6,472
  • 4
  • 32
  • 36
Mike Wills
  • 19,825
  • 26
  • 87
  • 143
  • 13
    If you're using ASP.Net Mvc I would recommend having a look at MvcMailer: https://github.com/smsohan/MvcMailer/wiki/MvcMailer-Step-by-Step-Guide – noocyte Oct 05 '11 at 07:42
  • please be aware of sender limits (I hope your band is successful enough that this is a problem) http://support.google.com/a/bin/answer.py?hl=en&answer=166852 – Simon_Weaver Jul 07 '13 at 20:54
  • easy way here read it. http://stackoverflow.com/questions/9201239/send-e-mail-via-smtp-using-c-sharp – Joel Santos Oct 07 '13 at 22:46
  • If you're doing a lot of work with email, Mail4Net is a great help. It allows you to unit test your email sending. – Karl Gjertsen Dec 02 '15 at 08:45
  • Please, look at the question http://stackoverflow.com/questions/34851484/how-to-send-an-email-in-net-according-to-new-google-security-policies –  Jan 19 '16 at 15:24
  • All the mostly redundant answers below essentially show you how to send an email after allowing less secure applications/devices. However, this may still not be enough if sending emails from a production server with a different IP or time zone. Please see this answer for a complete list of scenarios and solutions: http://stackoverflow.com/a/26709761/3440152 – Christoph May 15 '17 at 01:15
  • 1
    is probably the most absurdly complete site dedicated to a *single* .NET namespace...but it has EVERYTHING you could ever want to know about sending mail via .NET, be it ASP.NET or Desktop. * was the original URL in the post, but should not be used for .NET 2.0 and above.* – Adam Haile Aug 28 '08 at 13:36
  • One Tip! Check the sender inbox, maybe you need allow less secure apps. See: https://www.google.com/settings/security/lesssecureapps – Gustavo Rossi Muller Jul 21 '15 at 18:53
  • The problem for me was that my **password had a blackslash "\\"** in it, which I copy pasted without realizing it would cause problems. – Satbir Kira Jun 15 '15 at 11:34

22 Answers22

1103

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);
}
Sam
  • 6,961
  • 15
  • 44
  • 63
Domenic
  • 100,627
  • 39
  • 205
  • 257
  • 2
    When constructing the NetworkCredential, use fromAddress.Address, not .ToString() – SLaks Jun 16 '09 at 15:52
  • Note that this method could have the email being marked as spam, due to SPF (if it's implemented at the receiver). – Noon Silk Aug 15 '09 at 04:06
  • 51
    You can still get user not logged in errors if Google just suddenly decides you have sent too many in the past xx number of minutes. You should always add a trySend, if it errors sleep a while, and then attempt again. – Jason Short Aug 26 '09 at 06:30
  • 73
    Interesting note: If you swap 'UseDefaultCredentials = false,' and 'Credentials = ...' it won't authenticate. – Nathan Wheeler Nov 17 '09 at 16:56
  • 13
    There are no problems with SPF using this method. Every email client can be configured to do exactly this. You just may get problems if you use your own server (i.e. something else than `smtp.gmail.com`) with `something@gmail.com` as sender. Btw: `smtp.gmail.com` automatically overwrites the sender address if it's not yours. – Meinersbur Mar 18 '10 at 18:39
  • Gmail checks SPF for regular incoming mail (that are destined to `something@gmail.com`; the smtp server for this is `aspmx.l.google.com` port 25). Although Gmail implements and checks SPF for incoming mail, it currently seems that it does not use it to detect spam (afaik due to user complaints since it breaks forwarding). – Meinersbur Mar 18 '10 at 21:50
  • How to send a file using above code ? File means a textfile or some other file, which is located in C Drive. – Ranadheer Reddy May 28 '12 at 12:04
  • @domenic: Yes. Thank you. I just did that :) [sending email using c# with attachement](http://stackoverflow.com/questions/10782406/sending-mail-through-automation-c-mail-with-attachement) – Ranadheer Reddy May 29 '12 at 04:02
  • 24
    I was having a hard time getting this working even with trying various tweaks. As suggested on a related post, I found that it was actually my antivirus that was preventing emails from being successfully sent. The antivirus in question is McAffee, and its "Access Protection" has a "Antivirus Standard Protection" category that has a "Prevent mass mailing worms from sending email" rule. Tweaking / disabling that rule got this code working for me! – yourbuddypal Aug 05 '12 at 17:02
  • 2
    Just in case someone tumbles upon `System.InvalidOperationException: SSL authentication error: RemoteCertificateNotAvailable, RemoteCertificateChainErrors` you just need to set the `ServicePointManager.ServerCertificateValidationCallback` as [here](http://stackoverflow.com/questions/4148019/authentication-or-decryption-has-failed-when-sending-mail-to-gmail-using-ssl) – PCoder Feb 11 '13 at 15:19
  • 4
    I got error like 'The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.' How can I resolve this? – Sudha May 03 '13 at 09:13
  • 19
    I was getting the 5.5.1 Authentication Required error message until I realized I was testing with an account (my personal one) that had two factor authentication turned on. Once I used an account that didn't have that, it worked fine. I could also have generated a password for my application that I was testing from in my personal acct, but I didn't want to do that. – Nick DeVore Jun 17 '13 at 16:18
  • @NickDeVore I too am having authentication problems, and have 2-step authentication on. I have all the above stuff set up in my web.config instead of my controller and have generated a password for the app (due to 2-step auth) but still getting error. Any ideas? – J86 Aug 07 '14 at 21:27
  • @Ciwan I would make a fake gmail account without 2 factor auth and try it. If that works, then something with the two factor auth is preventing it from working. – Nick DeVore Aug 08 '14 at 05:31
  • 1
    For anyone struggling with the 5.5.1 Authentication Required message, make sure you set `UseDefaultCredentials = false` before setting the `Credentials` value. http://stackoverflow.com/a/11513412/356085 – PahJoker Nov 21 '14 at 02:29
  • One problem I've had with using gmail this way is that it seems to silently require a more complex password when sending automated emails. A problem when you have a test account with a simple password. – hangar Dec 25 '14 at 20:20
  • I was a able to turn down the authentication process easily with gmail. They first time you send a email, if you actually hit the server, the gmail team will ping you to let you know about the attempt. In that email it will have a link to the setting "access for less secure apps". – Chris Mar 25 '15 at 13:19
  • i used this same code but it did not work still. if some one facing authentication exception try http://stackoverflow.com/a/25414099/2649883 – Silver Apr 21 '15 at 13:29
  • I am using same code in Console application, it's through error **"Failure sending mail."** – Karthikeyan P Aug 26 '15 at 15:01
  • This answer doesnt work. Please, look at the question http://stackoverflow.com/questions/34851484/how-to-send-an-email-in-net-according-to-new-google-security-policies –  Jan 19 '16 at 15:21
  • 1
    @ivan_petrushenko (and others). The answer _does_ work, but in order to let my c# desktop app to use my account, I had to create a specific Google password for that app via Google> Account> Security> Apps> Manage apps> Add an app. That's a custom one named "MyNameApp on desktop PC", then google created a password for it. I changed the SMTP credential from my gmail password to that newly created one and it worked... hope that helps. – Karl Stephen Jan 31 '16 at 07:51
  • @KarlStephen Its an overhead.Why you should create a password? What if you need to send an email to yandex.ru or outlook.com? Thats mean that you need to remember three different pass etc. Or what if you don't have a permission to change account settings? –  Jan 31 '16 at 09:13
  • 1
    @ivan_petrushenko because 1) I like google policy about double security validation on my account. I don't want to allow whatever low level security apps to access my account or use my mail address to send whatever content to anyone, nor use complex APIs for what is basically a way to send SMTP mail through a C# code. BTW, no need to remember the app password at all, there are ways to make the app remember it. And 2) OP stated it was about a google account. But you're right : to get it working in most cases including non google accounts, you'll need much more code than above. :) – Karl Stephen Jan 31 '16 at 12:09
  • And here is explained what password to use if you have enabled two-factor authentication http://stackoverflow.com/questions/26736062/sending-email-fails-when-two-factor-authentication-is-on-for-gmail/27130058#27130058 – Stoyan Dimov Mar 10 '16 at 07:59
  • 1
    The GMAIL configuration setting to Allow Less Secure Applications is here ----> https://www.google.com/settings/security/lesssecureapps – Peter Morris Apr 29 '16 at 18:11
  • I would suggest to utilize smtp.SendMailAsync(message).ConfigureAwait(false) so you are not blocking the thread. – Gutek Jan 30 '18 at 14:53
  • 2
    According to [docs.microsoft.com](https://docs.microsoft.com/), the [`System.Net.Mail.SmtpClient` class](https://docs.microsoft.com/dotnet/api/system.net.mail.smtpclient) has been marked obsolete with the message "SmtpClient and its network of types are poorly designed, we strongly recommend you use [https://github.com/jstedfast/MailKit](https://github.com/jstedfast/MailKit) and [https://github.com/jstedfast/MimeKit](https://github.com/jstedfast/MimeKit) instead". – Lance U. Matthews Jun 01 '18 at 20:00
  • Came here to say what BACON said, can @sam update the answer please? https://docs.microsoft.com/en-us/dotnet/api/system.net.mail.smtpclient?view=netframework-4.7.2 – Vincent Buscarello Feb 22 '19 at 15:57
  • I have used same code and it works for me, here I have one more requirement like, how we can change the "mail delivery subsystem(mailer-daemon@googlemail.com to custom@zzz.com)" mail address to custom mail id. I mean when ever we send an email, let's assume mail got bounced(recipient not valid) and got back Delivery Status Notification (Failure) mail in that I want to change From address like noreply@zzz.com.Please advise on this issue – Venkat Nadendla Dec 13 '19 at 09:27
  • 1
    GMail sender have to enable insecure apps : https://myaccount.google.com/lesssecureapps – KhaledDev Nov 30 '20 at 10:17
159

The above answer doesn't work. You have to set DeliveryMethod = SmtpDeliveryMethod.Network or it will come back with a "client was not authenticated" error. Also it's always a good idea to put a timeout.

Revised code:

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

var fromAddress = new MailAddress("from@gmail.com", "From Name");
var toAddress = new MailAddress("to@yahoo.com", "To Name");
const string fromPassword = "password";
const string subject = "test";
const string body = "Hey now!!";

var smtp = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
    Timeout = 20000
};
using (var message = new MailMessage(fromAddress, toAddress)
{
    Subject = subject,
    Body = body
})
{
    smtp.Send(message);
}
nawfal
  • 62,042
  • 48
  • 302
  • 339
Donny V.
  • 19,411
  • 13
  • 59
  • 76
  • 3
    Interesting; it works on my machine (TM). But since this seems plausible, I'll add it to my answer. – Domenic Mar 16 '09 at 19:53
  • 3
    Hmm my guess is that SmtpDeliveryMethod.Network is the default, but maybe the default gets changed when running in IIS---was that what you were doing? – Domenic Mar 16 '09 at 19:55
  • 3
    I am using same code in Console application, it's through error **"Failure sending mail."** – Karthikeyan P Aug 26 '15 at 15:02
  • 5
    This answer doesnt work. Please, look at the question http://stackoverflow.com/questions/34851484/how-to-send-an-email-in-net-according-to-new-google-security-policies –  Jan 19 '16 at 15:22
123

For the other answers to work "from a server" first Turn On Access for less secure apps in the gmail account.

Looks like recently google changed it's security policy. The top rated answer no longer works, until you change your account settings as described here: https://support.google.com/accounts/answer/6010255?hl=en-GBenter image description here

enter image description here

As of March 2016, google changed the setting location again!

rogerdpack
  • 50,731
  • 31
  • 212
  • 332
BCS Software
  • 1,346
  • 1
  • 9
  • 8
  • 4
    This worked for me. And is also concerning. Not sure I want to turn that security off. May need to rethink... – Sully Apr 13 '16 at 12:41
  • 4
    From security point of view better to turn on 2-step Verification and then generate and use app password- see [How to send an email in .Net according to new security policies?](http://stackoverflow.com/a/34917400) – Michael Freidgeim Jun 05 '16 at 12:57
  • 2
    @BCS Software, inmy program, the user insert any email which my program has to use it to send the message throught. So, how I can make the email user able to send the email even if the 2-factor authentication is turned on?? – Alaa' Jan 18 '18 at 13:44
  • This is the same setting you need to alter if you wanted to use a Microsoft Outlook client (on a desktop, mobile phone, etc) to send/receive emails through Google's GMail. – Brett Rigby Apr 23 '19 at 10:44
  • This did the trick for me. But make sure you put it back as quickly as you can :) – Andrei Bazanov Oct 06 '20 at 09:10
43

This is to send email with attachement.. Simple and short..

source: http://coding-issues.blogspot.in/2012/11/sending-email-with-attachments-from-c.html

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

public void email_send()
{
    MailMessage mail = new MailMessage();
    SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
    mail.From = new MailAddress("your mail@gmail.com");
    mail.To.Add("to_mail@gmail.com");
    mail.Subject = "Test Mail - 1";
    mail.Body = "mail with attachment";

    System.Net.Mail.Attachment attachment;
    attachment = new System.Net.Mail.Attachment("c:/textfile.txt");
    mail.Attachments.Add(attachment);

    SmtpServer.Port = 587;
    SmtpServer.Credentials = new System.Net.NetworkCredential("your mail@gmail.com", "your password");
    SmtpServer.EnableSsl = true;

    SmtpServer.Send(mail);

}
Ranadheer Reddy
  • 3,930
  • 11
  • 49
  • 73
24

Google may block sign in attempts from some apps or devices that do not use modern security standards. Since these apps and devices are easier to break into, blocking them helps keep your account safer.

Some examples of apps that do not support the latest security standards include:

  • The Mail app on your iPhone or iPad with iOS 6 or below
  • The Mail app on your Windows phone preceding the 8.1 release
  • Some Desktop mail clients like Microsoft Outlook and Mozilla Thunderbird

Therefore, you have to enable Less Secure Sign-In in your google account.

After sign into google account, go to:

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

In C#, you can use the following code:

using (MailMessage mail = new MailMessage())
{
    mail.From = new MailAddress("email@gmail.com");
    mail.To.Add("somebody@domain.com");
    mail.Subject = "Hello World";
    mail.Body = "<h1>Hello</h1>";
    mail.IsBodyHtml = true;
    mail.Attachments.Add(new Attachment("C:\\file.zip"));

    using (SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587))
    {
        smtp.Credentials = new NetworkCredential("email@gmail.com", "password");
        smtp.EnableSsl = true;
        smtp.Send(mail);
    }
}
mjb
  • 6,155
  • 7
  • 35
  • 54
22

For me to get it to work, i had to enable my gmail account making it possible for other apps to gain access. This is done with the "enable less secure apps" and also using this link: https://accounts.google.com/b/0/DisplayUnlockCaptcha

rogerdpack
  • 50,731
  • 31
  • 212
  • 332
Mark Homans
  • 567
  • 1
  • 4
  • 12
17

Here is my version: "Send Email In C # Using Gmail".

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

namespace SendMailViaGmail
{
   class Program
   {
   static void Main(string[] args)
   {

      //Specify senders gmail address
      string SendersAddress = "Sendersaddress@gmail.com";
      //Specify The Address You want to sent Email To(can be any valid email address)
      string ReceiversAddress = "ReceiversAddress@yahoo.com";
      //Specify The password of gmial account u are using to sent mail(pw of sender@gmail.com)
      const string SendersPassword = "Password";
      //Write the subject of ur mail
      const string subject = "Testing";
      //Write the contents of your mail
      const string body = "Hi This Is my Mail From Gmail";

      try
      {
        //we will use Smtp client which allows us to send email using SMTP Protocol
        //i have specified the properties of SmtpClient smtp within{}
        //gmails smtp server name is smtp.gmail.com and port number is 587
        SmtpClient smtp = new SmtpClient
        {
           Host = "smtp.gmail.com",
           Port = 587,
           EnableSsl = true,
           DeliveryMethod = SmtpDeliveryMethod.Network,
           Credentials    = new NetworkCredential(SendersAddress, SendersPassword),
           Timeout = 3000
        };

        //MailMessage represents a mail message
        //it is 4 parameters(From,TO,subject,body)

        MailMessage message = new MailMessage(SendersAddress, ReceiversAddress, subject, body);
        /*WE use smtp sever we specified above to send the message(MailMessage message)*/

        smtp.Send(message);
        Console.WriteLine("Message Sent Successfully");
        Console.ReadKey();
     }

     catch (Exception ex)
     {
        Console.WriteLine(ex.Message);
        Console.ReadKey();
     }
    }
   }
 }
soumya
  • 3,627
  • 9
  • 33
  • 65
tehie
  • 179
  • 1
  • 2
  • 8
    While your article may in fact answer the question, [it would be preferable](http://meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference. Stack Overflow is only as useful as its questions and answers, and if your blog host goes down or your URLs get moved around, this answer becomes useless. Thanks! – sarnold Jan 16 '12 at 06:08
15

I hope this code will work fine. You can have a try.

// Include this.                
using System.Net.Mail;

string fromAddress = "xyz@gmail.com";
string mailPassword = "*****";       // Mail id password from where mail will be sent.
string messageBody = "Write the body of the message here.";


// Create smtp connection.
SmtpClient client = new SmtpClient();
client.Port = 587;//outgoing port for the mail.
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential(fromAddress, mailPassword);


// Fill the mail form.
var send_mail = new MailMessage();

send_mail.IsBodyHtml = true;
//address from where mail will be sent.
send_mail.From = new MailAddress("from@gmail.com");
//address to which mail will be sent.           
send_mail.To.Add(new MailAddress("to@example.com");
//subject of the mail.
send_mail.Subject = "put any subject here";

send_mail.Body = messageBody;
client.Send(send_mail);
Sam
  • 6,961
  • 15
  • 44
  • 63
Premdeep Mohanty
  • 751
  • 5
  • 10
  • 2
    message send_mail = new MailMessage(); How is this line suppose to work? You can't implicitly convert 'System.Net.Mail.MailMessage' to 'System.Windows.Forms.Message' – Debaprasad Mar 18 '14 at 06:23
10

Source : Send email in ASP.NET C#

Below is a sample working code for sending in a mail using C#, in the below example I am using google’s smtp server.

The code is pretty self explanatory, replace email and password with your email and password values.

public void SendEmail(string address, string subject, string message)
{
    string email = "yrshaikh.mail@gmail.com";
    string password = "put-your-GMAIL-password-here";

    var loginInfo = new NetworkCredential(email, password);
    var msg = new MailMessage();
    var smtpClient = new SmtpClient("smtp.gmail.com", 587);

    msg.From = new MailAddress(email);
    msg.To.Add(new MailAddress(address));
    msg.Subject = subject;
    msg.Body = message;
    msg.IsBodyHtml = true;

    smtpClient.EnableSsl = true;
    smtpClient.UseDefaultCredentials = false;
    smtpClient.Credentials = loginInfo;
    smtpClient.Send(msg);
}
Yasser Shaikh
  • 44,064
  • 44
  • 190
  • 271
  • Instead of var ,I have used class name like NetworkCredential,MailMessage and SmtpClient.It work for me. – Jui Test Feb 28 '13 at 07:33
  • 1
    This worked for me. Besides all the good points which are valid and mentioned above as well such as gmail security stuff mentioned above. The reason it worked was that one needs to switch off the default credentials of the object first, which are probably null or left empty BEFORE they can set their SmtpClient credentials, not AFTER. Thanks Yasser Shaikh. – Soliman Soliman Sep 15 '20 at 03:21
10

Include this,

using System.Net.Mail;

And then,

MailMessage sendmsg = new MailMessage(SendersAddress, ReceiversAddress, subject, body); 
SmtpClient client = new SmtpClient("smtp.gmail.com");

client.Port = Convert.ToInt16("587");
client.Credentials = new System.Net.NetworkCredential("mail-id@gmail.com","password");
client.EnableSsl = true;

client.Send(sendmsg);
Sam
  • 6,961
  • 15
  • 44
  • 63
GOPI
  • 1,010
  • 8
  • 29
8

If you want to send background email, then please do the below

 public void SendEmail(string address, string subject, string message)
 {
 Thread threadSendMails;
 threadSendMails = new Thread(delegate()
    {

      //Place your Code here 

     });
  threadSendMails.IsBackground = true;
  threadSendMails.Start();
}

and add namespace

using System.Threading;
Kevin Panko
  • 7,844
  • 19
  • 46
  • 58
RAJESH KUMAR
  • 457
  • 4
  • 12
8

To avoid security issues in Gmail, you should generate an app password first from your Gmail settings and you can use this password instead of a real password to send an email even if you use two steps verification.

Sayed Uz Zaman
  • 401
  • 6
  • 17
6

Try This,

    private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            MailMessage mail = new MailMessage();
            SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

            mail.From = new MailAddress("your_email_address@gmail.com");
            mail.To.Add("to_address");
            mail.Subject = "Test Mail";
            mail.Body = "This is for testing SMTP mail from GMAIL";

            SmtpServer.Port = 587;
            SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
            SmtpServer.EnableSsl = true;

            SmtpServer.Send(mail);
            MessageBox.Show("mail Send");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }
5

use this way

MailMessage sendmsg = new MailMessage(SendersAddress, ReceiversAddress, subject, body); 
SmtpClient client = new SmtpClient("smtp.gmail.com");

client.Port = Convert.ToInt32("587");
client.EnableSsl = true;
client.Credentials = new System.Net.NetworkCredential("mail-id@gmail.com","MyPassWord");
client.Send(sendmsg);

Don't forget this :

using System.Net;
using System.Net.Mail;
alireza amini
  • 1,616
  • 1
  • 16
  • 33
4

Changing sender on Gmail / Outlook.com email:

To prevent spoofing - Gmail/Outlook.com won't let you send from an arbitrary user account name.

If you have a limited number of senders you can follow these instructions and then set the From field to this address: Sending mail from a different address

If you are wanting to send from an arbitrary email address (such as a feedback form on website where the user enters their email and you don't want them emailing you directly) about the best you can do is this :

        msg.ReplyToList.Add(new System.Net.Mail.MailAddress(email, friendlyName));

This would let you just hit 'reply' in your email account to reply to the fan of your band on a feedback page, but they wouldn't get your actual email which would likely lead to a tonne of spam.

If you're in a controlled environment this works great, but please note that I've seen some email clients send to the from address even when reply-to is specified (I don't know which).

Simon_Weaver
  • 120,240
  • 73
  • 577
  • 618
4

I had the same issue, but it was resolved by going to gmail's security settings and Allowing Less Secure apps. The Code from Domenic & Donny works, but only if you enabled that setting

If you are signed in (to Google) you can follow this link and toggle "Turn on" for "Access for less secure apps"

DarkPh03n1X
  • 482
  • 4
  • 13
4
using System;
using System.Net;
using System.Net.Mail;

namespace SendMailViaGmail
{
   class Program
   {
   static void Main(string[] args)
   {

      //Specify senders gmail address
      string SendersAddress = "Sendersaddress@gmail.com";
      //Specify The Address You want to sent Email To(can be any valid email address)
      string ReceiversAddress = "ReceiversAddress@yahoo.com";
      //Specify The password of gmial account u are using to sent mail(pw of sender@gmail.com)
      const string SendersPassword = "Password";
      //Write the subject of ur mail
      const string subject = "Testing";
      //Write the contents of your mail
      const string body = "Hi This Is my Mail From Gmail";

      try
      {
        //we will use Smtp client which allows us to send email using SMTP Protocol
        //i have specified the properties of SmtpClient smtp within{}
        //gmails smtp server name is smtp.gmail.com and port number is 587
        SmtpClient smtp = new SmtpClient
        {
           Host = "smtp.gmail.com",
           Port = 587,
           EnableSsl = true,
           DeliveryMethod = SmtpDeliveryMethod.Network,
           Credentials = new NetworkCredential(SendersAddress, SendersPassword),
           Timeout = 3000
        };

        //MailMessage represents a mail message
        //it is 4 parameters(From,TO,subject,body)

        MailMessage message = new MailMessage(SendersAddress, ReceiversAddress, subject, body);
        /*WE use smtp sever we specified above to send the message(MailMessage message)*/

        smtp.Send(message);
        Console.WriteLine("Message Sent Successfully");
        Console.ReadKey();
     }
     catch (Exception ex)
     {
        Console.WriteLine(ex.Message);
        Console.ReadKey();
     }
}
}
}
Moin Shirazi
  • 4,116
  • 2
  • 23
  • 36
2

Here is one method to send mail and getting credentials from web.config:

public static string SendEmail(string To, string Subject, string Msg, bool bodyHtml = false, bool test = false, Stream AttachmentStream = null, string AttachmentType = null, string AttachmentFileName = null)
{
    try
    {
        System.Net.Mail.MailMessage newMsg = new System.Net.Mail.MailMessage(System.Configuration.ConfigurationManager.AppSettings["mailCfg"], To, Subject, Msg);
        newMsg.BodyEncoding = System.Text.Encoding.UTF8;
        newMsg.HeadersEncoding = System.Text.Encoding.UTF8;
        newMsg.SubjectEncoding = System.Text.Encoding.UTF8;

        System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();
        if (AttachmentStream != null && AttachmentType != null && AttachmentFileName != null)
        {
            System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(AttachmentStream, AttachmentFileName);
            System.Net.Mime.ContentDisposition disposition = attachment.ContentDisposition;
            disposition.FileName = AttachmentFileName;
            disposition.DispositionType = System.Net.Mime.DispositionTypeNames.Attachment;

            newMsg.Attachments.Add(attachment);
        }
        if (test)
        {
            smtpClient.PickupDirectoryLocation = "C:\\TestEmail";
            smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.SpecifiedPickupDirectory;
        }
        else
        {
            //smtpClient.EnableSsl = true;
        }

        newMsg.IsBodyHtml = bodyHtml;
        smtpClient.Send(newMsg);
        return SENT_OK;
    }
    catch (Exception ex)
    {

        return "Error: " + ex.Message
             + "<br/><br/>Inner Exception: "
             + ex.InnerException;
    }

}

And the corresponding section in web.config:

<appSettings>
    <add key="mailCfg" value="yourmail@example.com"/>
</appSettings>
<system.net>
  <mailSettings>
    <smtp deliveryMethod="Network" from="yourmail@example.com">
      <network defaultCredentials="false" host="mail.exapmple.com" userName="yourmail@example.com" password="your_password" port="25"/>
    </smtp>
  </mailSettings>
</system.net>
iTURTEV
  • 311
  • 1
  • 4
2

Try this one

public static bool Send(string receiverEmail, string ReceiverName, string subject, string body)
{
        MailMessage mailMessage = new MailMessage();
        MailAddress mailAddress = new MailAddress("abc@gmail.com", "Sender Name"); // abc@gmail.com = input Sender Email Address 
        mailMessage.From = mailAddress;
        mailAddress = new MailAddress(receiverEmail, ReceiverName);
        mailMessage.To.Add(mailAddress);
        mailMessage.Subject = subject;
        mailMessage.Body = body;
        mailMessage.IsBodyHtml = true;

        SmtpClient mailSender = new SmtpClient("smtp.gmail.com", 587)
        {
            EnableSsl = true,
            UseDefaultCredentials = false,
            DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network,
            Credentials = new NetworkCredential("abc@gmail.com", "pass")   // abc@gmail.com = input sender email address  
                                                                           //pass = sender email password
        };

        try
        {
            mailSender.Send(mailMessage);
            return true;
        }
        catch (SmtpFailedRecipientException ex)
        { 
          // Write the exception to a Log file.
        }
        catch (SmtpException ex)
        { 
           // Write the exception to a Log file.
        }
        finally
        {
            mailSender = null;
            mailMessage.Dispose();
        }
        return false;
}
David
  • 113
  • 10
reza.cse08
  • 5,172
  • 38
  • 34
1

Copying from another answer, the above methods work but gmail always replaces the "from" and "reply to" email with the actual sending gmail account. apparently there is a work around however:

http://karmic-development.blogspot.in/2013/10/send-email-from-aspnet-using-gmail-as.html

"3. In the Accounts Tab, Click on the link "Add another email address you own" then verify it"

Or possibly this

Update 3: Reader Derek Bennett says, "The solution is to go into your gmail Settings:Accounts and "Make default" an account other than your gmail account. This will cause gmail to re-write the From field with whatever the default account's email address is."

rogerdpack
  • 50,731
  • 31
  • 212
  • 332
1

You can try Mailkit. It gives you better and advance functionality for send mail. You can find more from this Here is an example

    MimeMessage message = new MimeMessage();
    message.From.Add(new MailboxAddress("FromName", "YOU_FROM_ADDRESS@gmail.com"));
    message.To.Add(new MailboxAddress("ToName", "YOU_TO_ADDRESS@gmail.com"));
    message.Subject = "MyEmailSubject";

    message.Body = new TextPart("plain")
    {
        Text = @"MyEmailBodyOnlyTextPart"
    };

    using (var client = new SmtpClient())
    {
        client.Connect("SERVER", 25); // 25 is port you can change accordingly

        // Note: since we don't have an OAuth2 token, disable
        // the XOAUTH2 authentication mechanism.
        client.AuthenticationMechanisms.Remove("XOAUTH2");

        // Note: only needed if the SMTP server requires authentication
        client.Authenticate("YOUR_USER_NAME", "YOUR_PASSWORD");

        client.Send(message);
        client.Disconnect(true);
    }
Naveen
  • 1,186
  • 1
  • 13
  • 35
0

How to Set App-specific password for gmail

If your Google password doesn't work, you may need to create an app-specific password for Gmail on Google. https://support.google.com/accounts/answer/185833?hl=en