.net framework 发送邮件实例

由于需要在Starlight Portal中提供邮件发送功能,所以在网上找了一些asp.net中发送邮件的文章,可是都不能满足需求。因为大部分的文章都介绍得很简单,只是告诉你怎么用MailMessage,而我想用Gmail的邮箱发送信件,因此会碰到一些额外的问题,比如:

  1. Gmail的Smtp端口不是默认的25,而是465
  2. Gmail的Smtp采用的是SSL连接

因此,要发送邮件,就必须解决这两个问题,其他的基本问题都可以很容易的找到解决方法。在这里记下代码,以供大家使用。 

 

MailMessage msg = new MailMessage();

    msg.From 
= settings.SystemEmailAccount;
    msg.To 
= to;
    msg.Subject 
= subject;
    msg.Body 
= body;

    
if(settings.SmtpAuthenticationRequired)
    
{
     msg.Fields.Add(
"http://schemas.microsoft.com/cdo/configuration/smtpauthenticate""1" ); 
     msg.Fields.Add(
"http://schemas.microsoft.com/cdo/configuration/sendusername", settings.SystemEmailAccount);
     msg.Fields.Add(
"http://schemas.microsoft.com/cdo/configuration/sendpassword", settings.SystemEmailAccountPassword);
    }


    
if(settings.SmtpPort != 25)
    
{
     msg.Fields.Add(
"http://schemas.microsoft.com/cdo/configuration/smtpserverport", settings.SmtpPort.ToString());
    }


    
if(settings.SmtpUseSSL)
    
{
     msg.Fields.Add(
"http://schemas.microsoft.com/cdo/configuration/smtpusessl""1");
    }


    SmtpMail.SmtpServer 
= settings.SmtpServer;
    SmtpMail.Send(msg);

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章