.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);

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