博客
关于我
C#实现邮件发送的功能
阅读量:178 次
发布时间:2019-02-28

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

发送邮件的核心技术与实现

在开发过程中,发送邮件是一个常用的功能模块。通过合理配置和调用相关类,可以实现邮件的发送功能。本文将详细介绍发送邮件所需的核心技术以及具体实现方法。

1.1 发送邮件的核心类

在开发过程中,发送邮件的核心类主要有 MyEmailSmtpClient。这些类分别负责邮件内容的处理和邮件传输的配置。

  • MyEmail:主要处理邮件的内容配置,包括接收方、发件方地址、邮件标题、邮件正文等信息。同时,还支持添加附件文件。

  • SmtpClient:负责通过 SMTP 协议发送邮件。该类内部封装了 SocketTcpClient 等低层通信组件,简化了邮件发送的开发过程。

1.2 邮件发送的配置参数

在使用 SmtpClient 类进行邮件发送时,需要配置以下几项参数:

  • 邮件服务器地址:可以是 IP 地址或 SMTP 服务器地址。
  • 发送端口号:默认为 25。
  • 验证方式:支持 NTLM 和其他验证方式。
  • SSL 加密:可选是否对邮件内容进行加密传输。
  • 1.3 具体代码示例

    以下是基于 C# 语言实现的邮件发送功能代码示例:

    using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Net.Mail;using System.Net.Mime;using System.IO;using System.Timers;using System.Xml;namespace MyEmailTest{    public class Program    {        public static void Main(string[] args)        {            try            {                string senderServerIp = "123.125.50.133"; // SMTP 服务器地址                string toMailAddress = "mingmingruyuedlut@163.com"; // 收件人地址                string fromMailAddress = "mingmingruyuedlut@163.com"; // 发件人地址                string subjectInfo = "Test sending e_mail"; // 邮件标题                string bodyInfo = "Hello Eric, This is my first testing e_mail"; // 邮件内容                string mailUsername = "mingmingruyuedlut"; // 发件箱用户名                string mailPassword = ".........."; // 发件箱密码                string mailPort = "25"; // 发件箱端口号                string attachPath = "E:\\123123.txt; E:\\haha.pdf"; // 附件路径                MyEmail email = new MyEmail(senderServerIp, toMailAddress, fromMailAddress, subjectInfo, bodyInfo, mailUsername, mailPassword, mailPort, false, false);                email.AddAttachments(attachPath);                email.Send();            }            catch (Exception ex)            {                Console.WriteLine(ex.ToString());            }        }    }    public class MyEmail    {        private MailMessage mMailMessage; // 邮件内容配置        private SmtpClient mSmtpClient; // SMTP 传输配置        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;                mSmtpClient = new SmtpClient();                mSmtpClient.Host = server;                mSmtpClient.Port = Convert.ToInt32(port);                mSmtpClient.UseDefaultCredentials = false;                mSmtpClient.EnableSsl = sslEnable;                if (pwdCheckEnable)                {                    mSmtpClient.Credentials = new System.Net.NetworkCredential(username, password);                }                else                {                    mSmtpClient.Credentials = new System.Net.NetworkCredential(username, password);                }                mSmtpClient.DeliveryMethod = 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());            }        }        public void Send()        {            try            {                if (mMailMessage != null)                {                    mSmtpClient = new SmtpClient();                    mSmtpClient.Host = mSenderServerHost;                    mSmtpClient.Port = mSenderPort;                    mSmtpClient.UseDefaultCredentials = false;                    mSmtpClient.EnableSsl = mEnableSsl;                    if (mEnablePwdAuthentication)                    {                        System.Net.NetworkCredential nc = new System.Net.NetworkCredential(mSenderUsername, mSenderPassword);                        mSmtpClient.Credentials = nc.GetCredential(mSmtpClient.Host, mSmtpClient.Port, "NTLM");                    }                    else                    {                        mSmtpClient.Credentials = new System.Net.NetworkCredential(mSenderUsername, mSenderPassword);                    }                    mSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;                    mSmtpClient.Send(mMailMessage);                }            }            catch (Exception ex)            {                Console.WriteLine(ex.ToString());            }        }    }}

    2. 结论

    通过上述代码示例,可以清晰地看到实现邮件发送功能所需的核心技术和配置步骤。MyEmail 类负责邮件内容的配置,而 SmtpClient 类则负责邮件的传输过程。通过合理配置相关参数,可以实现邮件的成功发送。

    转载地址:http://jnin.baihongyu.com/

    你可能感兴趣的文章
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>
    No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
    查看>>
    No module named cv2
    查看>>
    No module named tensorboard.main在安装tensorboardX的时候遇到的问题
    查看>>
    No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
    查看>>
    No new migrations found. Your system is up-to-date.
    查看>>
    No qualifying bean of type XXX found for dependency XXX.
    查看>>
    No resource identifier found for attribute 'srcCompat' in package的解决办法
    查看>>
    No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
    查看>>
    NO.23 ZenTaoPHP目录结构
    查看>>
    NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
    查看>>
    Node JS: < 一> 初识Node JS
    查看>>
    Node-RED中使用JSON数据建立web网站
    查看>>
    Node-RED中使用node-red-browser-utils节点实现选择Windows操作系统中的文件并实现图片预览
    查看>>
    Node-RED中使用Notification元件显示警告讯息框(温度过高提示)
    查看>>
    Node-RED中实现HTML表单提交和获取提交的内容
    查看>>
    Node.js 函数是什么样的?
    查看>>
    Node.js 实现类似于.php,.jsp的服务器页面技术,自动路由
    查看>>