Asp.net中使用System.Net.Mail發郵件方法總結

來源:互聯網
上載者:User

System.Net.Mail會讀取web.config中的配置,所以我們要在web.config中進行配置,配置如下:

 代碼如下 複製代碼

<system.net>
    <mailSettings>
        <smtp from="no-reply@gmail.com">
            <network host="smtpserver" port="25" userName="username" password="password" defaultCredentials="true" />
        </smtp>
    </mailSettings>
</system.net>

配置好後將它添加到web.config檔案中,放置在<configuration></configuration>節點中,不要忘了引入System.Net.Mail命名空間。接下來我們看看幾種發郵件的寫法:

1.Asp.net 發送普通文本郵件

 代碼如下 複製代碼

try
{
    MailMessage message = new MailMessage();
    //收件者
    message.To.Add(new MailAddress("google1@gmail.com"));
    message.To.Add(new MailAddress("google2@gmail.com"));

    //郵件標題
    message.Subject = "郵件標題";
    //郵件內文
    message.Body = "郵件內容";

    SmtpClient smtpClient = new SmtpClient();
    smtpClient.Send(message);
}
catch
{               
}

Send()方法可能會拋出異常,所以我們使用try來執行方法。

2.Asp.net 發送html格式的郵件

//只需將IsBodyHtml設定為true
message.Body = "這是一封html格式;的郵件";
message.IsBodyHtml = true;3.Asp.net 發送帶附件的郵件
//將附件添加進來即可
message.Attachments.Add(new Attachment("filename"));本篇介紹了在Asp.net中使用System.Net.Mail發送郵件的方法,如果你還想瞭解更多的話,可以在MSDN中找找System.Net.Mail命名空間來瞭解下。

舉例:

163.com的郵箱在早期申請的是支援的,後面申請的都是不支援。
21cn.com似乎現在已經放棄了smtp支援,可能只有繳費使用者才可以。
qq.com的郵箱需要在使用者帳戶裡面設定。

我拿了個sina.com的郵箱進行測試,也需要在後台裡面的

才可以發送。詳細代碼如下:

 代碼如下 複製代碼

MailAddress from = new MailAddress("sosuo8@sina.com");
MailAddress to = new MailAddress("ahuinan@21cn.com");
MailMessage message = new MailMessage(from, to);
message.Subject = "阿會楠的來信";
message.Body = "你好!測試而已";
SmtpClient client = new SmtpClient();
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Port = 25;
client.Host = "smtp.sina.com";
client.Credentials = new System.Net.NetworkCredential("sosuo8@sina.com", "123");
Response.Write("發送一份郵件到" + to.User + "," + to.Host +"," + client.Host);
client.Send(message);

別忘了引入命名空間:

 代碼如下 複製代碼

using System.Net;
using System.Net.Mail ;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.