I've had some problems sending emails from my gmail account too, which were due to several of the aforementioned situations.
Here's a summary of how I got it working, and keeping it flexible at the same time:
- First of all setup your GMail account:
- Enable IMAP and assert the right maximum number of messages (you can do so here)
- Make sure your password is at least 7 characters and is strong (according to Google)
- Make sure you don't have to enter a captcha code first. You can do so by sending a test email from your browser.
- Make changes in web.config (or app.config, I haven't tried that yet but I assume it's just as easy to make it work in a windows application):
<configuration>
<appSettings>
<add key="EnableSSLOnMail" value="True"/>
</appSettings>
<!-- other settings -->
...
<!-- system.net settings -->
<system.net>
<mailSettings>
<smtp from="[email protected]" deliveryMethod="Network">
<network
defaultCredentials="false"
host="smtp.gmail.com"
port="587"
password="stR0ngPassW0rd"
userName="[email protected]"
/>
<!-- 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
And now whenever you want to send emails all you need to do is call SSLMail.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("[email protected]")
SSLMail.SendMail(e)
End Sub
End Class
Or anywhere in your code you can call:
SSLMail.SendMail(New system.Net.Mail.MailMessage("[email protected]","[email protected]", "Subject", "Body"})
I hope this helps anyone who runs into this post! (I used VB.NET but I think it's trivial to convert it to any .NET language.)