.net 发送电邮_关于如何使用.NET发送电子邮件的快速参考

.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 发送电邮

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值