c# 發送帶附件的郵件

using System;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Text;

public class EmailUitls
    {
        /// <summary>
        /// 發送郵件
        /// </summary>
        /// <param name="fileName">附件路徑</param>
        /// <param name="name">發件人名字</param>
        /// <param name="eamil">接收郵箱</param>
        /// <param name="title">標題</param>
        /// <param name="content">內容</param>
        /// <returns>成功/失敗</returns>
        public static string send(string fileName, string name, string eamil, string title, string content)
        {
            SmtpClient client = new SmtpClient("smtp.qq.com");
            client.EnableSsl = true;
            client.UseDefaultCredentials = false;
            client.Credentials = new System.Net.NetworkCredential("發件人郵箱", "POP3/SMTP服務受權碼");

            MailAddress from = new MailAddress("發件人郵箱", name, Encoding.UTF8);//初始化發件人  

            MailAddress to = new MailAddress(eamil, "", Encoding.UTF8);//初始化收件人  

            //設置郵件內容  
            MailMessage message = new MailMessage(from, to);
            message.Body = content.Trim();
            message.BodyEncoding = Encoding.UTF8;
            message.Subject = title.Trim();
            message.SubjectEncoding = Encoding.UTF8;
            message.IsBodyHtml = false;

            if (!string.IsNullOrEmpty(fileName))
            {
                //附件
                Attachment myAttachment = new System.Net.Mail.Attachment(fileName, MediaTypeNames.Application.Octet);

                //MIME協議下的一個對象,用以設置附件的建立時間,修改時間以及讀取時間  
                ContentDisposition disposition = myAttachment.ContentDisposition;
                disposition.CreationDate = File.GetCreationTime(fileName);
                disposition.ModificationDate = File.GetLastWriteTime(fileName);
                disposition.ReadDate = File.GetLastAccessTime(fileName);

                //用smtpclient對象裏attachments屬性,添加上面設置好的myattachment  
                message.Attachments.Add(myAttachment);
            }

            try
            {
                client.Send(message);
                return "郵件發送成功!";
            }
            catch (Exception ex)
            {
                return "郵件發送失敗!" + ex.Message;
            }  
        }
    }

 有一個問題,附件太大會發送失敗 測試

 解決方法:https://support.microsoft.com/zh-cn/kb/2468871  (未測試)spa

相關文章
相關標籤/搜索