959

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
  • 7,904
  • 4
  • 42
  • 42
Mike Wills
  • 20,959
  • 28
  • 93
  • 149
  • 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
  • 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
  • You can find detailed steps on https://dsrawool.com/2022/09/11/setup-to-send-email-from-code-using-gmail-account/ – DSR Sep 11 '22 at 08:08

26 Answers26

1161

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.
iwis
  • 1,382
  • 1
  • 13
  • 26
Domenic
  • 110,262
  • 41
  • 219
  • 271
  • 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
  • 54
    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
  • 76
    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
  • 25
    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
  • 20
    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
  • 3
    According to [learn.microsoft.com](https://learn.microsoft.com/), the [`System.Net.Mail.SmtpClient` class](https://learn.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
  • 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 – boubkhaled Nov 30 '20 at 10:17
  • Anyone scrolling the comments just going to give a shout out to mail kit, puts the built in smtp to shame: https://github.com/jstedfast/MailKit – jjxtra Dec 17 '21 at 18:40
166

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
  • 70,104
  • 56
  • 326
  • 368
Donny V.
  • 22,248
  • 13
  • 65
  • 79
  • 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
159

Edit 2022 Starting May 30, 2022, ​​Google will no longer support the use of third-party apps or devices which ask you to sign in to your Google Account using only your username and password. But you still can send E-Mail via your gmail account.

  1. Go to https://myaccount.google.com/security and turn on two step verification. Confirm your account by phone if needed.
  2. Click "App Passwords", just below the "2 step verification" tick.
  3. Request a new password for the mail app. enter image description here

Now just use this password instead of the original one for you account!

public static void SendMail2Step(string SMTPServer, int SMTP_Port, string From, string Password, string To, string Subject, string Body, string[] FileNames) {            
            var smtpClient = new SmtpClient(SMTPServer, SMTP_Port) {
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                EnableSsl = true
            };                
            smtpClient.Credentials = new NetworkCredential(From, Password); //Use the new password, generated from google!
            var message = new System.Net.Mail.MailMessage(new System.Net.Mail.MailAddress(From, "SendMail2Step"), new System.Net.Mail.MailAddress(To, To));
            smtpClient.Send(message);
    }

Use like this:

SendMail2Step("smtp.gmail.com", 587, "youraccount@gmail.com",
          "yjkjcipfdfkytgqv",//This will be generated by google, copy it here.
          "recipient@barcodes.bg", "test message subject", "Test message body ...", null);

For the other answers to work "from a server" first Turn On Access for less secure apps in the gmail account. This will be deprecated 30 May 2022

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-GB As of March 2016, google changed the setting location again! enter image description here

BCS Software
  • 1,745
  • 1
  • 11
  • 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
  • 6
    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
46

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
  • 4,202
  • 12
  • 55
  • 77
25

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
  • 7,649
  • 8
  • 44
  • 60
24

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
  • 62,887
  • 36
  • 269
  • 388
Mark Homans
  • 637
  • 1
  • 6
  • 12
18

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,801
  • 9
  • 35
  • 69
tehie
  • 189
  • 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
16

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
  • 7,252
  • 16
  • 46
  • 65
Premdeep Mohanty
  • 761
  • 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
12

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
  • 46,934
  • 46
  • 204
  • 281
  • 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
12

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
  • 606
  • 1
  • 9
  • 25
  • Yes, I agree for gmail you will need to set this up. However i am not very keen on having a second less secure password with full access to my account. If you somehow can integrate "sign in with google" and store the token on the app it might be a better solution. However I have not tested this yet. – Cees Jan 26 '22 at 04:46
11

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 = 587;
client.Credentials = new System.Net.NetworkCredential("mail-id@gmail.com","password");
client.EnableSsl = true;

client.Send(sendmsg);
Community
  • 1
  • 1
GOPI
  • 1,042
  • 8
  • 30
9

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
  • 8,356
  • 19
  • 50
  • 61
RAJESH KUMAR
  • 497
  • 4
  • 13
7

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

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,712
  • 1
  • 18
  • 33
6

From 1 Jun 2022, ​​Google has added some security features

Google is no longer support the use of third-party apps or devices which ask you to sign in to your Google Account using only your username and password or send mail directly using username and password of google account. But you still can send E-Mail via your gmail account using generating app password.

Below are the steps for generate new password.

  1. Go to https://myaccount.google.com/security
  2. Turn on two step verification.
  3. Confirm your account by phone if needed.
  4. Click "App Passwords", just below the "2 step verification" tick. Request a new password for the mail app.

Now we have to use this password for sending mail instead of the original password of your account.

Below is the example code for sending mail

public static void SendMailFromApp(string SMTPServer, int SMTP_Port, string From, string Password, string To, string Subject, string Body) {            
            var smtpClient = new SmtpClient(SMTPServer, SMTP_Port) {
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                EnableSsl = true
            };                
            smtpClient.Credentials = new NetworkCredential(From, Password); //Use the new password, generated from google!
            var message = new System.Net.Mail.MailMessage(new System.Net.Mail.MailAddress(From, "SendMail2Step"), new System.Net.Mail.MailAddress(To, To));
            smtpClient.Send(message);
    }

You can to call method like below

SendMailFromApp("smtp.gmail.com", 25, "mygmailaccount@gmail.com",
          "tyugyyj1556jhghg",//This will be generated by google, copy it here.
          "mailme@gmail.com", "New Mail Subject", "Body of mail from My App");
Bhadresh Patel
  • 1,671
  • 17
  • 18
5

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
  • 140,023
  • 84
  • 646
  • 689
5

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
  • 600
  • 1
  • 7
  • 17
5
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,372
  • 2
  • 26
  • 38
3

enter image description here

Google has removed the less secure apps setting from our Google accounts, this means that we can no longer send emails from the SMTP server using our actual google passwords. We need to either use Xoauth2 and authorize the user or create a an apps password on an account that has 2fa enabled.

Once created an apps password can be used in place of your standard gmail password.

class Program
{
    private const string To = "test@test.com";
    private const string From = "test@test.com";
    
    private const string GoogleAppPassword = "XXXXXXXX";
    
    private const string Subject = "Test email";
    private const string Body = "<h1>Hello</h1>";
    
    
    static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");
        
        var smtpClient = new SmtpClient("smtp.gmail.com")
        {
            Port = 587,
            Credentials = new NetworkCredential(From , GoogleAppPassword),
            EnableSsl = true,
        };
        var mailMessage = new MailMessage
        {
            From = new MailAddress(From),
            Subject = Subject,
            Body = Body,
            IsBodyHtml = true,
        };
        mailMessage.To.Add(To);

        smtpClient.Send(mailMessage);
    }
}

Quick fix for SMTP username and password not accepted error

Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449
3

After google update, This is the valid method to send an email using c# or .net.

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 creating the app password, you can follow this article: https://www.techaeblogs.live/2022/06/how-to-send-email-using-gmail.html

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
  • 331
  • 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 Petric
  • 324
  • 3
  • 17
reza.cse08
  • 5,938
  • 48
  • 39
2

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,441
  • 2
  • 16
  • 41
2

This is no longer supported incase you are trying to do this now.

https://support.google.com/accounts/answer/6010255?hl=en&visit_id=637960864118404117-800836189&p=less-secure-apps&rd=1#zippy=

enter image description here

Sunny Okoro Awa
  • 523
  • 4
  • 9
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
  • 62,887
  • 36
  • 269
  • 388
1

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