c# 發送郵件、附件

來源:互聯網
上載者:User

標籤:c#   winform   郵件發送附件   

WinForm表單代碼如下:

<span style="font-size:14px;">using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;<span style="color:#ff0000;">//要添加的引用如下</span>using System.Net.Mail;using System.Net.Mime;using System.Timers;using System.IO;namespace NovelCS {    public partial class Form3 : Form {        public Form3() {            InitializeComponent();        }                   private void Form3_Load(object sender, EventArgs e) {            //一些常見的發送郵件伺服器地址 一般都是 stmp.**.com   **=qq 或 126 或163 或 gmail 有例外的,具體問度娘            string senderServerIp = "smtp.qq.com";                       string toMailAddress = "[email protected]";            string fromMailAddress = "[email protected]";            string subjectInfo = "My First Email";            string bodyInfo [email protected]"Hello Jackerson, \r\n                                        This is my first testing e_mail.But what all thess is from  an author named Eric Sun.                                        Thank you,Eric Sun.";            string mailUsername = "1449740504";            string mailPassword = "******"; //發送人郵箱的密碼            string mailPort = "25";   //郵箱連接埠號碼            string attachPath = "D:\\jsj.txt; D:\\jsj2.txt";//附件本地地址            MyEmail email = new MyEmail(senderServerIp, toMailAddress, fromMailAddress, subjectInfo, bodyInfo, mailUsername, mailPassword, mailPort, false, false);            email.AddAttachments(attachPath);            email.Send();        }                   }    public class MyEmail {        private MailMessage me;//主要處理髮送郵件的內容,例:收寄件者地址、標題、主體、圖片        private SmtpClient sc;   //主要處理用smtp發送郵件的配置資訊,例:發送郵件伺服器地址、傳送埠號、驗證方式        private int mSenderPort;                         //發送郵件所用的連接埠號碼(htmp協議預設為25)        private string mSenderServerHost;          //寄件匣的郵件伺服器地址(IP形式或字串形式均可)        private string mSenderUserName;           //寄件匣的使用者名稱(即@符號前面的字串,例如:[email protected],使用者名稱為:hello)        private string mSenderPassword;             //寄件匣的密碼        private bool mEnableSsl;                         //是否對郵件內容進行socket層加密傳輸        private bool mEnablePwdAuthentication;  //是否對寄件者郵箱進行密碼驗證        ///<summary>        /// <strong><span style="color:#ff0000;">建構函式</span></strong>        ///</summary>        ///<param name="server">寄件匣的郵件伺服器地址</param>        ///<param name="toMail">收件者地址(可以是多個收件者,程式中是以“;"進行區分的)</param>        ///<param name="fromMail">寄件者地址</param>        ///<param name="subject">郵件標題</param>        ///<param name="emailBody">郵件內容(可以以html格式進行設計)</param>        ///<param name="username">寄件匣的使用者名稱(即@符號前面的字串,例如:[email protected],使用者名稱為:hello)</param>        ///<param name="password">寄件者郵箱密碼</param>        ///<param name="port">發送郵件所用的連接埠號碼(htmp協議預設為25)</param>        ///<param name="sslEnable">true表示對郵件內容進行socket層加密傳輸,false表示不加密</param>        ///<param name="pwdCheckEnable">true表示對寄件者郵箱進行密碼驗證,false表示不對寄件者郵箱進行密碼驗證</param>        public MyEmail(string server, string toMailAddress, string fromMailAddress, string emailTitle, string emailBody, string username, string password, string port, bool sslEnable, bool pwdCheckEnable) {            try {                me = new MailMessage();                me.To.Add(toMailAddress);                me.From = new MailAddress(fromMailAddress);                me.Subject = emailTitle;                me.Body = emailBody;                me.IsBodyHtml = true;                me.BodyEncoding = System.Text.Encoding.UTF8;                me.Priority = MailPriority.Normal;                this.mSenderServerHost = server;                this.mSenderUserName = username;                this.mSenderPassword = password;                this.mSenderPort = Convert.ToInt32(port);                this.mEnableSsl = sslEnable;                this.mEnablePwdAuthentication = pwdCheckEnable;            } catch (Exception ex) {                MessageBox.Show(ex.ToString());            }        }        ///<summary>        /// <strong><span style="color:#ff0000;">添加附件</span></strong>        ///</summary>        ///<param name="attachmentsPath">附件的路徑集合,以分號分隔</param>        public void AddAttachments(string attachmentsPath) {            try {                string[] path = attachmentsPath.Split(';'); //以什麼符號分隔可以自訂                Attachment data;                ContentDisposition disposition;                for (int i = 0; i < path.Length; i++) {                    data = new Attachment(path[i], MediaTypeNames.Application.Octet);                    disposition = data.ContentDisposition;                    disposition.CreationDate = File.GetCreationTime(path[i]);                    disposition.ModificationDate = File.GetLastWriteTime(path[i]);                    disposition.ReadDate = File.GetLastAccessTime(path[i]);                    me.Attachments.Add(data);                }            } catch (Exception ex) {                MessageBox.Show(ex.ToString());            }        }        ///<summary>        /// <strong><span style="color:#ff0000;">郵件的發送</span></strong>        ///</summary>        public void Send() {            try {                if (me != null) {                    sc = new SmtpClient();                    //mSmtpClient.Host = "smtp." + mMailMessage.From.Host;                    sc.Host = this.mSenderServerHost;                    sc.Port = this.mSenderPort;                    sc.UseDefaultCredentials = false;                    sc.EnableSsl = this.mEnableSsl;                    if (this.mEnablePwdAuthentication) {                        System.Net.NetworkCredential nc = new System.Net.NetworkCredential(this.mSenderUserName, this.mSenderPassword);                        //mSmtpClient.Credentials = new System.Net.NetworkCredential(this.mSenderUsername, this.mSenderPassword);                        //NTLM: Secure Password Authentication in Microsoft Outlook Express                        sc.Credentials = nc.GetCredential(sc.Host, sc.Port, "NTLM");                    } else {                        sc.Credentials = new System.Net.NetworkCredential(this.mSenderUserName, this.mSenderPassword);                    }                    sc.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;                    sc.Send(me);                }            } catch (Exception ex) {                Console.WriteLine(ex.ToString());            }        }    }            }</span>

備忘:

(1)經過測試,確實可以使用。

(2)本文出處:Eric Sun(http://www.cnblogs.com/mingmingruyuedlut/archive/2011/10/14/2212255.html)

c# 發送郵件、附件

聯繫我們

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