博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C#实现邮件发送的功能
阅读量:5011 次
发布时间:2019-06-12

本文共 6217 字,大约阅读时间需要 20 分钟。

1.实现原理:

  • 微软封装好的MailMessage类:主要处理发送邮件的内容(如:收发人地址、标题、主体、图片等等)
  • 微软封装好的SmtpClient类:主要处理用smtp方式发送此邮件的配置信息(如:邮件服务器、发送端口号、验证方式等等)
  • SmtpClient主要进行了三层的封装:Socket --> TcpClient --> SmtpClient

2.构建帮助工具类:

using System;using System.IO;using System.Net.Mail;using System.Net.Mime;public class MyEmail{        private MailMessage mMailMessage;   //主要处理发送邮件的内容(如:收发人地址、标题、主体、图片等等)        private SmtpClient mSmtpClient; //主要处理用smtp方式发送此邮件的配置信息(如:邮件服务器、发送端口号、验证方式等等)        private int mSenderPort;   //发送邮件所用的端口号(htmp协议默认为25)        private string mSenderServerHost;    //发件箱的邮件服务器地址(IP形式或字符串形式均可)        private string mSenderPassword;    //发件箱的密码        private string mSenderUsername;   //发件箱的用户名(即@符号前面的字符串,例如:hello@163.com,用户名为:hello)        private bool mEnableSsl;    //是否对邮件内容进行socket层加密传输        private bool mEnablePwdAuthentication;  //是否对发件人邮箱进行密码验证        ///        /// 构造函数        ///        ///发件箱的邮件服务器地址        ///收件人地址(可以是多个收件人,程序中是以“;"进行区分的)        ///发件人地址        ///邮件标题        ///邮件内容(可以以html格式进行设计)        ///发件箱的用户名(即@符号前面的字符串,例如:hello@163.com,用户名为:hello)        ///发件人邮箱密码        ///发送邮件所用的端口号(htmp协议默认为25)        ///true表示对邮件内容进行socket层加密传输,false表示不加密        ///true表示对发件人邮箱进行密码验证,false表示不对发件人邮箱进行密码验证        public MyEmail(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());            }        }        ///        /// 邮件的发送        ///        public void Send()        {            try            {                if (mMailMessage != null)                {                    mSmtpClient = new SmtpClient();                    //mSmtpClient.Host = "smtp." + mMailMessage.From.Host;                    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());            }        }        ///        /// 添加附件        ///        ///附件的路径集合,以分号分隔        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());            }        }}

3.控制台相关代码

static void Main(string[] args){            try            {                //smtp.163.com                //string senderServerIp = "123.125.50.133";                //smtp.gmail.com                //string senderServerIp = "74.125.127.109";                //smtp.qq.com                string senderServerIp = "smtp.qq.com";//qq邮箱的smtp地址                //string senderServerIp = "smtp.sina.com";                string toMailAddress = "1277529182@qq.com";//收件人的邮箱地址                string fromMailAddress = "1277529182@qq.com";//发件人的邮箱地址                string subjectInfo = "Test";//主题                string bodyInfo = "This is test email";//内容                string mailUsername = "1277529182";//邮箱的用户名                string mailPassword = "111"; //发送邮箱的密码(如果是QQ邮箱需要配置客户端密码)                string mailPort = "25";//端口                //string attachPath = "E:\\123123.txt; E:\\haha.pdf";//添加的附件                MyEmail email = new MyEmail(senderServerIp, toMailAddress, fromMailAddress, subjectInfo, bodyInfo, mailUsername, mailPassword, mailPort, true, true);                //email.AddAttachments(attachPath);                email.Send();            }            catch (Exception ex)            {                Console.WriteLine(ex.ToString());            }}

4.需要身份验证的邮箱SMTP,例如QQ邮箱,则需要配置客户端密码:

开启SMTP服务
786645-20190102181435873-1153452618.png

786645-20190102181456093-1680628672.png

最后使用生成的授权码填入到【发送邮箱的密码】

转载于:https://www.cnblogs.com/ButterflyEffect/p/10210391.html

你可能感兴趣的文章
android 实现2张图片层叠效果
查看>>
我个人所有的独立博客wordpress都被挂马
查看>>
html5——动画案例(时钟)
查看>>
调用Android系统“应用程序信息(Application Info)”界面
查看>>
ios中用drawRect方法绘图的时候设置颜色
查看>>
Django 基于session认证 小作业
查看>>
数据库中的外键和主键理解
查看>>
个人博客03
查看>>
Expression<Func<T,TResult>>和Func<T,TResult>
查看>>
文件缓存
查看>>
关于C语言中return的一些总结
查看>>
Codeforces Round #278 (Div. 2)
查看>>
51. N-Queens
查看>>
Linux 命令 - 文件搜索命令 locate
查看>>
CTFMON。exe
查看>>
spark
查看>>
[Angular] Angular Global Keyboard Handling With EventManager
查看>>
[Python] Execute a Python Script
查看>>
[Angular 2] Using Promise to Http
查看>>
[Grunt] grunt.template
查看>>