.net 发送电邮
介绍许多.NET应用程序出于各种原因都需要发送电子邮件。 本文将提供有关如何使用VB.NET发送电子邮件的快速示例。 给出的示例可以轻松转换为C#.NET。
存储电子邮件凭证如果您正在开发Web应用程序,则存储电子邮件凭据的最佳位置是web.config文件的<appSettings>中。 这将使您能够使用加密保护电子邮件凭据,并为所有代码提供访问单个凭据的位置。
<configuration>
<appSettings>
<add key="EmailUserName" value="userName"/>
<add key="EmailPassword" value="password"/>
</appSettings>
</configuration>
如果您使用的是.NET Framework 1.1版
您将必须导入System.Web.Mail
该框架不会轻易允许您提供允许您连接到邮件服务器的电子邮件凭据。 我不会在本文中介绍如何执行此操作。
Dim mailMsg As Mail.MailMessage
Dim body As new String = "This will be the body of my email message"
mailMsg= New MailMessage
mailMsg.To= "to@blabla.com"
mailMsg.From= "from@blabla.com"
mailMsg.Subject = "The subject of the email"
mailMsg.BodyFormat = MailFormat.Html
mailMsg.Body = body
SmtpMail.SmtpServer="localhost"
Try
SmtpMail.Send(mailMsg)
Catch ex As Exception
End Try
如果您没有使用.NET Framework 1.1版
您将必须导入System.Net.Mail.MailMessage,并且如果需要提供电子邮件凭据才能连接到邮件服务器System.Net.NetworkCredentials
请注意,以下代码段显示了如何从web.config文件中检索用户凭据。 如果您不将凭据存储在此文件中,则只需为用户名和密码添加字符串,而不是使用ConfigureationManager.AppSettings(...)来提供凭据。
同样,如果您不必提供用户凭据即可连接到邮件提供商,则在此示例中,您可以忽略与凭据有关的任何事情
Try
Dim emailTitle As String ="My Email Title"
Dim emailMessage As Net.Mail.MailMessage
Dim body As String = "This will appear in the body of my email"
emailMessage = New Net.Mail.MailMessage("from@emailAddress.com", "to@emailAddress.com", emailTitle, body)
Dim mailClient As New Net.Mail.SmtpClient("urlOfEmailService.com", 25)
'25 is the port on which the mail server is listening. If your mail server
'runs on the default port this number does not need to be provided
'If you do not need to provide credentials to connect to the mail server you can ignore the next 3 lines
Dim myCredentials As New System.Net.NetworkCredential(System.Configuration.ConfigurationManager.AppSettings("EmailUserName"), System.Configuration.ConfigurationManager.AppSettings("EmailPassword"))
mailClient.UseDefaultCredentials = False
mailClient.Credentials = myCredentials
mailClient.Send(emailMessage)
Catch ex As Exception
End Try
希望对您有所帮助!
-弗林尼
翻译自: https://bytes.com/topic/net/insights/648873-quick-reference-how-send-email-using-net
.net 发送电邮