Coder Perfect

Using C# to send email using the Gmail SMTP server

Problem

For some reason, neither the accepted nor any alternative answers for “Sending email in.NET over Gmail” work for me. What makes you think they won’t work?

UPDATE: I tried all of the allowed and non-accepted responses in the other question, but none of them worked.

I’m just curious if it works for anyone else, since Google could have changed something (which has happened before).

I soon obtain a SmtpException on Send when I try the code that utilizes SmtpDeliveryMethod.Network (message). The message is clear.

The answer from the server was:

UPDATE:

This is a query I’ve had for a long time, and the accepted response is code that I’ve used on a variety of projects.

I created an EmailSender project on Codeplex based on some of the ideas in this post and other EmailSender projects. It’s built to be testable and works with my favorite SMTP providers, such as GoDaddy and Gmail.

Asked by CVertex

Solution #1

Make careful to review your code, CVertex, and upload it if it doesn’t disclose anything. This is something I just enabled on a test ASP.NET site I’m working on, and it works.

Actually, I experienced a problem with my code at one point. It wasn’t until I tried a simpler version on a console program and saw that it worked that I noticed it (no change on the Gmail side as you were worried about). The below code works just like the samples you referred to:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            var client = new SmtpClient("smtp.gmail.com", 587)
            {
                Credentials = new NetworkCredential("myusername@gmail.com", "mypwd"),
                EnableSsl = true
            };
            client.Send("myusername@gmail.com", "myusername@gmail.com", "test", "testbody");
            Console.WriteLine("Sent");
            Console.ReadLine();
        }
    }
}

I also got it to work using a mix of web.config, http://msdn.microsoft.com/en-us/library/w355a94k.aspx, and http://msdn.microsoft.com/en-us/library/w355a94k.aspx. and code (since the configuration file doesn’t have a corresponding EnableSsl: ( ).

Access for “less secure applications” must also be enabled in your gmail settings page: google.com/settings/security/lesssecureapps. If you’re getting the exception “‘, you’ll need to do this. 5.5.1 Authentication Required was the server response. — courtesy of @Ravendarksky

Answered by eglasius

Solution #2

IF ALL ELSE FAILS, THE FOLLOWING WILL Almost Certainly BE THE ANSWER TO YOUR QUESTION:

I received the same issue; it turns out that Google’s new password strength testing algorithm has changed, finding my current password to be too weak and not informing me (not even a message or warning)… How did I find out about this? Well, I chose to change my password to see if it would help (tried everything else to no avail) and when I changed my password, it worked!

Then, as a test, I tried changing my password back to my old one to see what would happen, but Gmail wouldn’t let me, claiming that “unfortunately we cannot enable you to save this change as your selected password is too weak” and refusing to let me go back to my old password. I deduced that it was failing because either a) you must update your password once per x number of months or b) you must change your password every x number of months. As I previously stated, their password strength algorithms changed, and as a result, the weak password I had was no longer accepted, despite the fact that they made no mention of this when I attempted to login anywhere! This is the most likely outcome (number 2), as

It’s a shame they didn’t say anything about it, but it makes sense. Because most hijacked emails are logged into using software other than gmail, and I’m betting that if you wish to utilize Gmail outside of the Gmail environment, you’ll need a stronger password.

Answered by Erx_VB.NExT.Coder

Solution #3

In addition to the other troubleshooting methods listed above, if you have two-factor authentication (also known as two-step verification) set on your GMail account, you must create an application-specific password and use that password to login via SMTP.

To generate a password, go to https://www.google.com/settings/ and select Authorizing applications & sites.

Answered by John Rasch

Solution #4

Turn On Access For Less Secure Apps and it will work for all no need to change password.

Link to Gmail Configuration

Answered by Suhail Mumtaz Awan

Solution #5

I’ve had some problems sending emails from my gmail account too, which were due to several of the aforementioned situations. Here’s a quick rundown of how I got it to work while remaining flexible:

<configuration>
    <appSettings>
        <add key="EnableSSLOnMail" value="True"/>   
    </appSettings>

    <!-- other settings --> 

    ...

    <!-- system.net settings -->
    <system.net>
        <mailSettings>
            <smtp from="yourusername@gmail.com" deliveryMethod="Network">
                <network 
                    defaultCredentials="false" 
                    host="smtp.gmail.com" 
                    port="587" 
                    password="stR0ngPassW0rd" 
                    userName="yourusername@gmail.com"
                    />
                <!-- When using .Net 4.0 (or later) add attribute: enableSsl="true" and you're all set-->
            </smtp>
        </mailSettings>
    </system.net>
</configuration>
Add a Class to your project:

Imports System.Net.Mail

Public Class SSLMail

    Public Shared Sub SendMail(ByVal e As System.Web.UI.WebControls.MailMessageEventArgs)

        GetSmtpClient.Send(e.Message)

        'Since the message is sent here, set cancel=true so the original SmtpClient will not try to send the message too:
        e.Cancel = True

    End Sub

    Public Shared Sub SendMail(ByVal Msg As MailMessage)
        GetSmtpClient.Send(Msg)
    End Sub

    Public Shared Function GetSmtpClient() As SmtpClient

        Dim smtp As New Net.Mail.SmtpClient
        'Read EnableSSL setting from web.config
        smtp.EnableSsl = CBool(ConfigurationManager.AppSettings("EnableSSLOnMail"))
        Return smtp
    End Function

End Class

All you have to do now is call SSLMail everytime you want to send an email. SendMail:

e.g. in a Page with a PasswordRecovery control:

Partial Class RecoverPassword
Inherits System.Web.UI.Page

Protected Sub RecoverPwd_SendingMail(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.MailMessageEventArgs) Handles RecoverPwd.SendingMail
    e.Message.Bcc.Add("webmaster@example.com")
    SSLMail.SendMail(e)
End Sub

End Class

You can call it from anywhere in your code.

SSLMail.SendMail(New system.Net.Mail.MailMessage("from@from.com","to@to.com", "Subject", "Body"})

I hope this information is useful to anyone who comes across this site! (I used VB.NET, but I believe it would be easy to convert to any.NET language.)

Answered by Sebas

Post is based on https://stackoverflow.com/questions/704636/sending-email-through-gmail-smtp-server-with-c-sharp