發送郵件的幾種方法

來源:互聯網
上載者:User
 

使用System.Web.Mail發送郵件:

public void SendMail()
{
    MailMessage mail1 = new MailMessage();
    mail1.Body="body here";  //郵件的本文
    mail1.From="xxx@your.com";  //發信人的地址
    mail1.To="yyy@their.com";   //收信人的地址
    mail1.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate",1);  //要求smtp認證
    mail1.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername","xxx");  //smtp認證的使用者
    mail1.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword","********");  //smtp認證的密碼
    SmtpMail.SmtpServer="mail.your.com";  //smtp伺服器
    SmtpMail.Send(mail1);  //發送郵件
}

使用System.Net.Mail發送郵件:
發現用這種方式發郵件,如果發郵件的電腦開啟了殺毒軟體的郵件監控,會有錯誤提示,但能夠發信成功。

1)第一種方式:先配置web.config檔案
<system.net>
    <mailSettings>
        <smtp from="your@your.com">
            <network host="smtp.your.com" port="25" userName="your" password="yourpass" />
        </smtp>
    </mailSettings>
</system.net>

然後通下面的程式發信:
private void SendMail()
{
    SmtpClient smtp = new SmtpClient();
    MailMessage message = new MailMessage();
    message.To.Add("to@yourmail.com");  //收信人地址
    message.SubjectEncoding = System.Text.Encoding.UTF8;  //主題文字編碼方式
    message.BodyEncoding = System.Text.Encoding.UTF8;  //內容文字編碼方式

    message.Subject = "A test for sending mail";  //主題
    message.Body = "Thanks for your sending mail./n/n";  //內容

    smtp.Send(message);  //發信
    message.Dispose();
}

2)第二種方式是不配置web.config檔案,直接通過下面的程式發信:
private void SendMail()
{
    SmtpClient smtp = new SmtpClient("mail.your.com", 25);
    smtp.Credentials = new System.Net.NetworkCredential("from@your.com", "yourpass");  //提供發信smtp認證資訊
    MailAddress from = new MailAddress("from@your.com", "tiger", System.Text.Encoding.UTF8);  //發信人資訊
    MailAddress to = new MailAddress("to@their.com");  //收信人資訊
    MailMessage message = new MailMessage(from, to);
    message.Subject = "這裡是主題";
    message.Body = "本文內容";
    message.SubjectEncoding = System.Text.Encoding.UTF8;
    message.BodyEncoding = System.Text.Encoding.UTF8;
    smtp.Send(message);
    message.Dispose();
}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.