c# 傳送郵件程式碼,帶附件

xuxubaby發表於2013-10-14
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net;
using System.Diagnostics;
 
namespace Test28
{
    class Program
    {
        static void Main(string[] args)
        {
            Email email = new Email()
            {
                fromEmail = "傳送人郵箱",
                fromPerson = "發件人",
                toEmail = "接收人郵箱",
                toPerson = "接收人",
                encoding = "UTF-8",
                smtpServer = "選用的郵件伺服器平【比如:mail.163.com】",
                userName = "你郵箱的使用者名稱【比如:xxxxx@163.com】",
                passWord = "你的郵箱的密碼",
                emailTitle = "郵件標題",
                emailContent = "郵件內容"
            };
            SendEmail(email);
        }
 
        #region 郵件傳送程式碼
        /// <summary>
        /// 郵件傳送程式碼
        /// </summary>
        /// <param name="email"></param>
        public static void SendEmail(Email email)
        {
            //try
            //{
            //設定發件人信箱,及顯示名字
            MailAddress from = new MailAddress(email.fromEmail, email.fromPerson);
            //設定收件人信箱,及顯示名字
            MailAddress to = new MailAddress(email.toEmail, email.toPerson);
            //建立一個MailMessage物件
            MailMessage oMail = new MailMessage(from, to);
            oMail.Subject = email.emailTitle; //郵件標題
            oMail.Body = email.emailContent; //郵件內容
            oMail.IsBodyHtml = true; //指定郵件格式,支援HTML格式
            System.Net.Mail.Attachment mailAttach_1 = new   Attachment(@"c:\UserCenterLog.txt");//附件
            oMail.Attachments.Add(mailAttach_1);
            oMail.BodyEncoding = System.Text.Encoding.GetEncoding(email.encoding);//郵件採用的編碼
            oMail.Priority = MailPriority.High;//設定郵件的優先順序為高
            //傳送郵件伺服器
            SmtpClient client = new SmtpClient();
            client.Host = email.smtpServer; //指定郵件伺服器
            client.Credentials = new NetworkCredential(email.userName, email.passWord);//指定伺服器郵件,及密碼
            //傳送
            client.Send(oMail); //傳送郵件
            oMail.Dispose(); //釋放資源
            //}
            //catch(Exception ex)
            //{
            //    StreamWriter writer = File.AppendText(@"c:\00.txt");
            //    writer.WriteLine(ex.Message);
            //    writer.Close();
            //    writer.Dispose();
            //}
            //finally
            //{
 
            //}
        }
        #endregion
    }
 
    class Email
    {
        public string fromEmail { get; set; }
        public string fromPerson { get; set; }
        public string toEmail { get; set; }
        public string toPerson { get; set; }
        public string encoding { get; set; }
        public string smtpServer { get; set; }
        public string userName { get; set; }
        public string passWord { get; set; }
        public string emailTitle { get; set; }
        public string emailContent { get; set; }
    }
}


 

相關文章