.NET(C#):使用SmtpClient發送帶有圖片和附件的電子郵件

來源:互聯網
上載者:User

第一次使用這種方式發郵件呵呵,就比如拿我的Live郵箱往QQ郵箱上發一封郵件。

使用SmtpClient發送郵件的步驟就不講了,在網上你可以找到太多的資料了,這裡說一些需要注意的地方:

如果郵件的內容是HTML,設定MailMessage.IsBodyHtml為True,這樣郵件才能夠被正確以HTML形式讀取。

 

在HTML中引用資源使用cid:xxx,xxx是附件的ContentId屬性。同時也可以在MailMessage中的AlternateViews中加入AlternateView來指定電子郵件內容的不同格式。通過AlternativeView的LinkedResources來加入引用檔案。引用也是通過LinkedResource的ContentId來設定的。事實上這個ContentId屬性是來自AttachmentBase類型,而Attachment,AlternateView和LinkedResource類型都繼承與這個類:

 

另外郵件的內容,主題,位址名稱如果包含某些非ASCII字元的話應該指定一個編碼,因為預設編碼是ASCII。

最後某些SMTP伺服器可能不支援SSL傳輸,因此SmtpClient的EnableSsl只能為false(否則會有異常拋出)。

 

代碼:

using System;

using System.Text;

using System.Net;

using System.Net.Mime;

using System.Net.Mail;

 

namespace Mgen

{

    class Program

    {

        static void Main()

        {

            //代碼中的某些資訊(如郵箱和密碼)已用xxx代替,因此如果編譯代碼,請先替換成有效資料!

            using (var smtp = new SmtpClient())

            using (var mail = new MailMessage("xxx@live.com", "xxx@qq.com"))

            {

                //映像附件

                var attach = new Attachment(@"D:\a.jpg", MediaTypeNames.Image.Jpeg);

                //設定ContentId

                attach.ContentId = "pic";

                //ZIP附件

                var attach2 = new Attachment(@"D:\b.zip", "application/x-zip-compressed");

 

                mail.Attachments.Add(attach);

                mail.Attachments.Add(attach2);

 

                //標題和內容,注意設定編碼,因為預設編碼是ASCII

                mail.Subject = "你好";

                mail.SubjectEncoding = Encoding.UTF8;

                //HTML內容

                mail.Body = "<img src=\"cid:pic\"/><p>來自Mgen。</p>";

                mail.BodyEncoding = Encoding.UTF8;

 

                //指示改電子郵件內容是HTML格式

                mail.IsBodyHtml = true;

 

                //SMTP設定(根據郵箱類型設定,這裡是Live Mail的SMTP伺服器位址)

                smtp.Host = "smtp.live.com";

                smtp.UseDefaultCredentials = false;

                //某些SMTP伺服器可能不支援SSL,會拋出異常

                smtp.EnableSsl = true;

                smtp.Credentials = new NetworkCredential("xxx@live.com", "xxx");

                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;

 

                //發送

                smtp.Send(mail);

            }

        }

    }

}

 

最後在QQ郵箱中瀏覽接收到的郵件:

相關文章

聯繫我們

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