Sending email in .NET through Gmail
Asked Answered
C

26

964

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?

Cherry answered 28/8, 2008 at 13:28 Comment(9)
If you're using ASP.Net Mvc I would recommend having a look at MvcMailer: github.com/smsohan/MvcMailer/wiki/MvcMailer-Step-by-Step-GuideMerow
please be aware of sender limits (I hope your band is successful enough that this is a problem) support.google.com/a/bin/answer.py?hl=en&answer=166852Lientery
easy way here read it. #9201739Candycandyce
The problem for me was that my password had a blackslash "\\" in it, which I copy pasted without realizing it would cause problems.Sawhorse
One Tip! Check the sender inbox, maybe you need allow less secure apps. See: google.com/settings/security/lesssecureappsCookhouse
If you're doing a lot of work with email, Mail4Net is a great help. It allows you to unit test your email sending.Chaldean
Please, look at the question #34851984Czarra
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: https://mcmap.net/q/22199/-gmail-error-the-smtp-server-requires-a-secure-connection-or-the-client-was-not-authenticated-the-server-response-was-5-5-1-authentication-requiredDorsey
You can find detailed steps on dsrawool.com/2022/09/11/…Prisage
F
1168

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("[email protected]", "From Name");
var toAddress = new MailAddress("[email protected]", "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.
Footpace answered 28/8, 2008 at 14:8 Comment(30)
When constructing the NetworkCredential, use fromAddress.Address, not .ToString()Wane
Note that this method could have the email being marked as spam, due to SPF (if it's implemented at the receiver).Kimberlykimberlyn
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.Under
Interesting note: If you swap 'UseDefaultCredentials = false,' and 'Credentials = ...' it won't authenticate.Mugwump
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 [email protected] as sender. Btw: smtp.gmail.com automatically overwrites the sender address if it's not yours.Equivalent
Gmail checks SPF for regular incoming mail (that are destined to [email protected]; 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).Equivalent
How to send a file using above code ? File means a textfile or some other file, which is located in C Drive.Moncton
@domenic: Yes. Thank you. I just did that :) sending email using c# with attachementMoncton
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!Lassitude
Just in case someone tumbles upon System.InvalidOperationException: SSL authentication error: RemoteCertificateNotAvailable, RemoteCertificateChainErrors you just need to set the ServicePointManager.ServerCertificateValidationCallback as hereMoulder
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?Lazybones
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.Mercurous
@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?Simonton
@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.Mercurous
For anyone struggling with the 5.5.1 Authentication Required message, make sure you set UseDefaultCredentials = false before setting the Credentials value. https://mcmap.net/q/22201/-can-39-t-auth-to-gmail-smtp-via-mailmessage-amp-smtpclientCalv
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.Amylum
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".Adenectomy
i used this same code but it did not work still. if some one facing authentication exception try https://mcmap.net/q/22201/-can-39-t-auth-to-gmail-smtp-via-mailmessage-amp-smtpclientPelson
I am using same code in Console application, it's through error "Failure sending mail."Gingergingerbread
This answer doesnt work. Please, look at the question #34851984Czarra
@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.Bergman
@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?Czarra
@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. :)Bergman
And here is explained what password to use if you have enabled two-factor authentication #26736562Indemnify
The GMAIL configuration setting to Allow Less Secure Applications is here ----> google.com/settings/security/lesssecureappsAspasia
I would suggest to utilize smtp.SendMailAsync(message).ConfigureAwait(false) so you are not blocking the thread.Stook
According to learn.microsoft.com, the System.Net.Mail.SmtpClient class 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 and https://github.com/jstedfast/MimeKit instead".Shavonneshaw
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([email protected] to [email protected])" 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 [email protected] advise on this issuePanslavism
GMail sender have to enable insecure apps : myaccount.google.com/lesssecureappsWesterly
Anyone scrolling the comments just going to give a shout out to mail kit, puts the built in smtp to shame: github.com/jstedfast/MailKitKillian
K
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("[email protected]", "From Name");
var toAddress = new MailAddress("[email protected]", "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);
}
Kurtz answered 28/1, 2009 at 22:1 Comment(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?Footpace
I am using same code in Console application, it's through error "Failure sending mail."Gingergingerbread
This answer doesnt work. Please, look at the question #34851984Czarra
H
161

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, "[email protected]",
          "yjkjcipfdfkytgqv",//This will be generated by google, copy it here.
          "[email protected]", "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

Harriman answered 8/9, 2015 at 12:9 Comment(5)
This worked for me. And is also concerning. Not sure I want to turn that security off. May need to rethink...Flump
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?Latrinalatrine
@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??Zoster
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.Decal
This did the trick for me. But make sure you put it back as quickly as you can :)Skipton
M
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 [email protected]");
    mail.To.Add("[email protected]");
    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 [email protected]", "your password");
    SmtpServer.EnableSsl = true;

    SmtpServer.Send(mail);

}
Moncton answered 28/5, 2012 at 12:41 Comment(0)
F
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 protected]");
    mail.To.Add("[email protected]");
    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 protected]", "password");
        smtp.EnableSsl = true;
        smtp.Send(mail);
    }
}
Fanti answered 9/8, 2014 at 7:28 Comment(0)
H
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

Henebry answered 3/1, 2014 at 15:25 Comment(0)
F
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 = "[email protected]";
      //Specify The Address You want to sent Email To(can be any valid email address)
      string ReceiversAddress = "[email protected]";
      //Specify The password of gmial account u are using to sent mail(pw of [email protected])
      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();
     }
    }
   }
 }
Filippo answered 17/10, 2010 at 21:19 Comment(1)
While your article may in fact answer the question, it would be preferable 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!Batfowl
P
16

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

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

string fromAddress = "[email protected]";
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("[email protected]");
//address to which mail will be sent.           
send_mail.To.Add(new MailAddress("[email protected]");
//subject of the mail.
send_mail.Subject = "put any subject here";

send_mail.Body = messageBody;
client.Send(send_mail);
Pugilism answered 15/10, 2013 at 10:0 Comment(1)
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'Olmsted
G
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 = "[email protected]";
    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);
}
Gunter answered 22/8, 2012 at 12:29 Comment(2)
Instead of var ,I have used class name like NetworkCredential,MailMessage and SmtpClient.It work for me.Costin
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.Tumultuous
T
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.

Tony answered 17/7, 2019 at 1:23 Comment(1)
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.Voncile
S
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("[email protected]","password");
client.EnableSsl = true;

client.Send(sendmsg);
Stockroom answered 9/10, 2013 at 12:39 Comment(0)
D
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;
Dunigan answered 23/7, 2013 at 9:47 Comment(0)
A
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("[email protected]");
            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());
        }
    }
Abey answered 31/1, 2017 at 8:23 Comment(0)
C
7

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, "[email protected]",
          "tyugyyj1556jhghg",//This will be generated by google, copy it here.
          "[email protected]", "New Mail Subject", "Body of mail from My App");
Condense answered 13/10, 2022 at 11:23 Comment(0)
V
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("[email protected]","MyPassWord");
client.Send(sendmsg);

Don't forget this :

using System.Net;
using System.Net.Mail;
Vedda answered 9/7, 2015 at 6:57 Comment(0)
L
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).

Lientery answered 7/7, 2013 at 20:49 Comment(0)
K
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"

Kinata answered 25/6, 2015 at 7:9 Comment(0)
O
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 = "[email protected]";
      //Specify The Address You want to sent Email To(can be any valid email address)
      string ReceiversAddress = "[email protected]";
      //Specify The password of gmial account u are using to sent mail(pw of [email protected])
      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();
     }
}
}
}
Orian answered 10/10, 2015 at 13:57 Comment(0)
S
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 = "[email protected]";
    private const string From = "[email protected]";
    
    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

Shipe answered 11/11, 2022 at 15:32 Comment(0)
C
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

Culottes answered 18/12, 2022 at 11:37 Comment(0)
B
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="[email protected]"/>
</appSettings>
<system.net>
  <mailSettings>
    <smtp deliveryMethod="Network" from="[email protected]">
      <network defaultCredentials="false" host="mail.exapmple.com" userName="[email protected]" password="your_password" port="25"/>
    </smtp>
  </mailSettings>
</system.net>
Bordelon answered 8/10, 2013 at 6:10 Comment(0)
C
2

Try this one

public static bool Send(string receiverEmail, string ReceiverName, string subject, string body)
{
        MailMessage mailMessage = new MailMessage();
        MailAddress mailAddress = new MailAddress("[email protected]", "Sender Name"); // [email protected] = 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("[email protected]", "pass")   // [email protected] = 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;
}
Clastic answered 27/2, 2016 at 12:40 Comment(0)
Q
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", "[email protected]"));
    message.To.Add(new MailboxAddress("ToName", "[email protected]"));
    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);
    }
Quade answered 3/6, 2019 at 8:31 Comment(0)
I
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

Inutile answered 14/8, 2022 at 15:8 Comment(0)
N
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."

Narceine answered 22/3, 2018 at 13:7 Comment(0)
B
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

Bricky answered 7/9, 2020 at 18:33 Comment(1)
This is a comment.Getz

© 2022 - 2024 — McMap. All rights reserved.