我也从我的gmail帐户发送电子邮件时遇到了一些问题,这是由于上述几种情况引起的。这是我如何使其工作并同时保持灵活性的摘要:
- 首先,设置您的GMail帐户:
- 启用IMAP并声明正确的最大消息数(您可以在此处这样做)
- 确保您的密码至少7个字符且安全性高(根据Google)
- 确保您不必先输入验证码。您可以通过从浏览器发送测试电子邮件来做到这一点。
- 在web.config中进行更改(或app.config,我还没有尝试过,但是我想让它在Windows应用程序中工作同样容易):
<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
现在,每当您要发送电子邮件时,您需要做的只是致电SSLMail.SendMail
:
例如在具有PasswordRecovery控件的页面中:
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
您也可以在代码中的任何位置调用:
SSLMail.SendMail(New system.Net.Mail.MailMessage("from@from.com","to@to.com", "Subject", "Body"})
我希望这对遇到这篇文章的人有所帮助!(我使用了VB.NET,但我认为将其转换为任何.NET语言很简单。)