Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using MailMessage to send emails in C#

Tags:

c#

mailmessage

I am experiencing some problems sending emails with MailMessage. I have two email accounts, ([email protected], and [email protected]) and I would like account2 to send an email to account one at a button click event.

This is what I have but it's not working. I'm getting and exception saying it's forbidden.

            try
            {
                //do submit
                MailMessage emailMessage = new MailMessage();
                emailMessage.From = new MailAddress("[email protected]", "Account2");
                emailMessage.To.Add(new MailAddress("[email protected]", "Account1"));
                emailMessage.Subject = "SUBJECT";
                emailMessage.Body = "BODY";
                emailMessage.Priority = MailPriority.Normal;
                SmtpClient MailClient = new SmtpClient("smtp.gmail.com");
                MailClient.Credentials = new System.Net.NetworkCredential("[email protected]", "password");
                MailClient.Send(emailMessage);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

I have a feeling it's a problem with the Smtp but I have no clue.

like image 264
Zac Voicheq Avatar asked Jul 31 '13 06:07

Zac Voicheq


People also ask

How do I send an email using MailKit?

C# send simple mail with Mailkit Net. Smtp; using MailKit. Security; using MimeKit; var host = "smtp.mailtrap.io"; var port = 2525; var username = "username"; // get from Mailtrap var password = "password"; // get from Mailtrap var message = new MimeMessage(); message.

Is SmtpClient obsolete?

The SmtpClient class is obsolete in Xamarin. However: It is included in the . NET Standard 2.0 and later versions and therefore must be part of any .


1 Answers

Try this:

using (MailMessage emailMessage = new MailMessage())
{
    emailMessage.From = new MailAddress("[email protected]", "Account2");
    emailMessage.To.Add(new MailAddress("[email protected]", "Account1"));
    emailMessage.Subject = "SUBJECT";
    emailMessage.Body = "BODY";
    emailMessage.Priority = MailPriority.Normal;
    using (SmtpClient MailClient = new SmtpClient("smtp.gmail.com", 587))
    {
        MailClient.EnableSsl = true;
        MailClient.Credentials = new System.Net.NetworkCredential("[email protected]", "password");
        MailClient.Send(emailMessage);
    }                               
} 

I added the port to the smtp client and enabled SSL. If port 587 doesn't work, try port 465.

like image 103
Loetn Avatar answered Nov 03 '22 01:11

Loetn