• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# 发送邮件附件

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

最近要做一个发送邮件的功能,依稀记得曾经有做过相似的东西,翻看了以前保存的项目代码,果然有(虽然已经不记得是怎么完成的了)。

完整项目就不贴了,有个Helper.cs,把这个贴上来吧,实际业务需要,新增了添加附件的方法。

public class EmailHelper
    {
        private MailMessage mMailMessage;   //主要处理发送邮件的内容(如:收发人地址、标题、主体、图片等等)
        private SmtpClient mSmtpClient; //主要处理用smtp方式发送此邮件的配置信息(如:邮件服务器、发送端口号、验证方式等等)
        private int mSenderPort;   //发送邮件所用的端口号(htmp协议默认为25)
        private string mSenderServerHost;    //发件箱的邮件服务器地址(IP形式或字符串形式均可)
        private string mSenderPassword;    //发件箱的密码
        private string mSenderUsername;   //发件箱的用户名(即@符号前面的字符串,例如:[email protected],用户名为:hello)
        private bool mEnableSsl;    //是否对邮件内容进行socket层加密传输
        private bool mEnablePwdAuthentication;  //是否对发件人邮箱进行密码验证

        ///<summary>
        /// 构造函数
        ///</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 EmailHelper(string server, string toMail, string fromMail, string subject, string emailBody, string username, string password, string port, bool sslEnable, bool pwdCheckEnable)
        {
            try
            {
                mMailMessage = new MailMessage();
                mMailMessage.To.Add(toMail);
                mMailMessage.From = new MailAddress(fromMail);
                mMailMessage.Subject = subject;
                mMailMessage.Body = emailBody;
                mMailMessage.IsBodyHtml = true;
                mMailMessage.BodyEncoding = System.Text.Encoding.UTF8;
                mMailMessage.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)
            {
                Console.WriteLine(ex.ToString());
            }
        }

        ///<summary>
        /// 添加附件
        ///</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]);
                    mMailMessage.Attachments.Add(data);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
        ///<summary>
        /// 添加附件
        ///</summary>
        ///<param name="stream">网络附件,上传Stream流</param>
        public void AddAttachments(Stream stream, string name)
        {
            try
            {
                //string[] path = attachmentsPath.Split(\';\'); //以什么符号分隔可以自定义
                Attachment data;
                data = new Attachment(stream, name);
                mMailMessage.Attachments.Add(data);

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

        ///<summary>
        /// 发送邮件
        ///</summary>
        public void Send()
        {
            try
            {
                if (mMailMessage != null)
                {
                    //建立发送对象client,验证邮件服务器,服务器端口,用户名,以及密码
                    mSmtpClient = new SmtpClient();
                    mSmtpClient.Host = this.mSenderServerHost;
                    mSmtpClient.Port = this.mSenderPort;
                    mSmtpClient.UseDefaultCredentials = false;
                    mSmtpClient.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
                        mSmtpClient.Credentials = nc.GetCredential(mSmtpClient.Host, mSmtpClient.Port, "NTLM");
                    }
                    else
                    {
                        mSmtpClient.Credentials = new System.Net.NetworkCredential(this.mSenderUsername, this.mSenderPassword);
                    }
                    mSmtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                    mSmtpClient.Send(mMailMessage);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
    }

 

 添加附件,分为绝对路径与网络路径两种

添加绝对路径很简单

//添加本地附件
emailHelper.AddAttachments("C:\\附件1.txt");
//发送邮件
emailHelper.Send();

网络路径则通过Steam流上传文件

string url = "https://pic.cnblogs.com/avatar/35695/20201013225735.png";
WebClient web = new WebClient();
//从网络路径下载资源作为 Byte 数组
byte[] a = web.DownloadData(url); Stream s = new MemoryStream(a); string name = url.Substring(url.LastIndexOf("."));
//通过Stream添加附件 emailHelper.AddAttachments(s,
"博客园团队" + name);
//发送邮件
emailHelper.Send();

 

排坑:

1、腾讯企业邮箱,smtp发送服务器是 “smtp.exmail.qq.com”,官方给出的是465,我使用587端口,使用其他端口发布到服务器上,我这儿提示超时。具体587与465端口的区别,找到一个歪果仁的贴子自己看吧 https://stackoverflow.com/questions/15796530/what-is-the-difference-between-ports-465-and-587

2、网易邮箱,有个很带劲的操作,”授权密码“,网易需要自己新增一个“授权码”(是用于登录第三方邮件客户端的专用密码)

 

 

不以物喜,不以己悲。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#有关虚方法要知道的知识点:发布时间:2022-07-14
下一篇:
深入C#的String类发布时间:2022-07-14
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap