我在从我的 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 语言都很简单。)