C#邮件发送


代码截图

代码截图

EmailInfo.cs

class EmailInfo
{
    /// <summary>
    /// 服务器IP
    /// </summary>
    public string ServerHost { get; set; }
    /// <summary>
    /// 端口号
    /// </summary>
    public int ServerPort { get; set; }
    /// <summary>
    /// 登录邮件发送服务器的用户名
    /// </summary>
    public string UserName { get; set; }
    /// <summary>
    /// 登录邮件发送服务器的密码
    /// </summary>
    public string Password { get; set; }
    //是否对邮件内容进行socket层加密传输
    public bool mEnableSsl { get; set; }
    /// <summary>
    /// 是否对发件人邮箱进行密码验证
    /// </summary>
    public bool mEnablePwdAuthentication { get; set; }

    /// <summary>
    /// 发送者的邮件地址
    /// </summary>
    public string fromAddress { get; set; }
    /// <summary>
    /// 邮件接收者地址,多个用,隔开
    /// </summary>
    public string toAddress { get; set; }
    /// <summary>
    /// 附件列表
    /// </summary>
    public List<AttachModel> AttachFileNames { get; set; }
    /// <summary>
    /// 邮件主题
    /// </summary>
    public string Subject { get; set; }
    /// <summary>
    /// 邮件内容
    /// </summary>

    public string Content { get; set; }

    public EmailInfo()
    {
        AttachFileNames = new List<AttachModel>();
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="filePath">附件路径</param>
    /// <param name="AttachFileName">发送的附件重命名名称</param>
    public void addAttachFileName(string filePath, string AttachFileName)
    {
        AttachFileNames.Add(new AttachModel()
        {
            FilePath = filePath,
            ReName = AttachFileName
        });
    }
    public class AttachModel
    {
        public string FilePath { get; set; }
        public string ReName { get; set; }
    }
}
GarsonZhang www.yesdotnet.com

 

EailHelper.cs

internal class EailHelper
{
    internal static SendEMailStatus sendMail(EmailInfo mailinfo)
    {
        SendEMailStatus status = new SendEMailStatus();

        try
        {
            using (MailMessage mMailMessage = new MailMessage())
            {
                //设置邮件信息
                mMailMessage.From = new MailAddress(mailinfo.fromAddress);
                mMailMessage.To.Add(mailinfo.toAddress);
                mMailMessage.Subject = mailinfo.Subject;
                mMailMessage.Body = mailinfo.Content;
                mMailMessage.IsBodyHtml = true;
                mMailMessage.BodyEncoding = System.Text.Encoding.UTF8;
                mMailMessage.Priority = MailPriority.Normal;

                //添加附件
                try
                {
                    Attachment data;
                    ContentDisposition disposition;
                    foreach (var v in mailinfo.AttachFileNames)
                    {
                        data = new Attachment(v.FilePath, MediaTypeNames.Application.Octet);
                        data.Name = v.ReName;
                        disposition = data.ContentDisposition;
                        disposition.CreationDate = File.GetCreationTime(v.FilePath);
                        disposition.ModificationDate = File.GetLastWriteTime(v.FilePath);
                        disposition.ReadDate = File.GetLastAccessTime(v.FilePath);
                        mMailMessage.Attachments.Add(data);
                    }
                }
                catch (Exception ex)
                {
                    Logs.Log.Error(ex, "邮件发送异常");
                    status.success = false;
                    status.message = ex.ToString();
                    return status;
                }

                using (SmtpClient mSmtpClient = new SmtpClient())
                {
                    mSmtpClient.Host = mailinfo.ServerHost;
                    mSmtpClient.Port = mailinfo.ServerPort;
                    mSmtpClient.UseDefaultCredentials = false;
                    mSmtpClient.EnableSsl = mailinfo.mEnableSsl;
                    if (mailinfo.mEnablePwdAuthentication)
                    {
                        System.Net.NetworkCredential nc = new System.Net.NetworkCredential(mailinfo.UserName, mailinfo.Password);
                        //mSmtpClient.Credentials = new System.Net.NetworkCredential(this.mSenderUsername, this.mSenderPassword);
                        //NTLM: Secure Password Authentication in Microsoft Outlook Express
                        mSmtpClient.Credentials = nc;
                        //mSmtpClient.Credentials = nc.GetCredfEnableSslential(mSmtpClient.Host, mSmtpClient.Port, "NTLM");
                    }
                    else
                    {
                        mSmtpClient.Credentials = new System.Net.NetworkCredential(mailinfo.UserName, mailinfo.Password);

                    }
                    mSmtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                    mSmtpClient.Timeout = 10 * 1000;
                    mSmtpClient.Send(mMailMessage);
                }
                status.success = true;
                return status;
            }
        }
        catch (Exception ex)
        {
            Logs.Log.Error(ex, "邮件发送异常");
            status.success = false;
            status.message = ex.ToString();
            return status;
        }
    }
}
GarsonZhang www.yesdotnet.com

 

SendEMailStatus.cs

public class SendEMailStatus
{
    public bool success { get; set; }
    public string message { get; set; }
}
GarsonZhang www.yesdotnet.com

 

EmailProvider

public class EmailProvider
{
    EmailInfo mailInfo;
    public EmailProvider()
    {
        mailInfo = new EmailInfo();

        mailInfo.ServerHost = GlobalData.EmailConfigData.ServerHost;
        mailInfo.ServerPort = GlobalData.EmailConfigData.ServerPort;
        mailInfo.mEnablePwdAuthentication = GlobalData.EmailConfigData.mEnablePwdAuthentication;
        mailInfo.UserName = GlobalData.EmailConfigData.UserName;
        mailInfo.Password = GlobalData.EmailConfigData.Password;
        mailInfo.fromAddress = GlobalData.EmailConfigData.FromAddress;
        mailInfo.mEnableSsl = GlobalData.EmailConfigData.mEnableSsl;

        //mailInfo.ServerHost = "mail.china.com";
        //mailInfo.ServerPort = 25;
        //mailInfo.mEnablePwdAuthentication = true;
        //mailInfo.UserName = "***@china.com";
        //mailInfo.Password = "***";
        //mailInfo.fromAddress = "***@china.com";
        //mailInfo.mEnableSsl = false;
    }

    public SendEMailStatus sendEmail(String toEmailAddress, String subject, String content)
    {
        if (String.IsNullOrEmpty(toEmailAddress)) return new SendEMailStatus()
        {
            success = false,
            message = "邮箱地址为空!",
        };
        mailInfo.toAddress = toEmailAddress;

        mailInfo.Subject = subject;
        mailInfo.Content = content;
        mailInfo.AttachFileNames.Clear();

        return EailHelper.sendMail(mailInfo);

    }
    public SendEMailStatus sendEmail(String toEmailAddress, String subject, String content, String filePath, String AttachFileName)
    {
        mailInfo.toAddress = toEmailAddress;

        mailInfo.Subject = subject;
        mailInfo.Content = content;
        mailInfo.AttachFileNames.Clear();
        mailInfo.addAttachFileName(filePath, AttachFileName);

        return EailHelper.sendMail(mailInfo);

    }
}
GarsonZhang www.yesdotnet.com

 

使用

全局配置 GlobalData.cs

public class GlobalData
{
    public static EmailConfig EmailConfigData { get; set; }
    public static void LoadData(IConfiguration Configuration)
    {
        EmailConfig emailConfig = new EmailConfig()
        {
            ServerHost = Configuration.GetValue<string>($"EmailConfig:{nameof(EmailConfig.ServerHost)}"),
            ServerPort = Configuration.GetValue<int>($"EmailConfig:{nameof(EmailConfig.ServerPort)}"),
            mEnablePwdAuthentication = Configuration.GetValue<bool>($"EmailConfig:{nameof(EmailConfig.mEnablePwdAuthentication)}"),
            UserName = Configuration.GetValue<string>($"EmailConfig:{nameof(EmailConfig.UserName)}"),
            Password = Configuration.GetValue<string>($"EmailConfig:{nameof(EmailConfig.Password)}"),
            FromAddress = Configuration.GetValue<string>($"EmailConfig:{nameof(EmailConfig.FromAddress)}"),
            mEnableSsl = Configuration.GetValue<bool>($"EmailConfig:{nameof(EmailConfig.mEnableSsl)}")
        };

        GlobalData.EmailConfigData = emailConfig;
    }

    public static void UpdateEmailConfigData(EmailConfig data)
    {
        var filePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "appsettings.json");
        JObject jsonObject;
        using StreamReader file = new StreamReader(filePath);
        using (JsonTextReader reader = new JsonTextReader(file))
        {
            jsonObject = (JObject)JToken.ReadFrom(reader);
            jsonObject["EmailConfig"][nameof(EmailConfig.ServerHost)] = data.ServerHost;
            jsonObject["EmailConfig"][nameof(EmailConfig.ServerPort)] = data.ServerPort;
            jsonObject["EmailConfig"][nameof(EmailConfig.mEnablePwdAuthentication)] = data.mEnablePwdAuthentication;
            jsonObject["EmailConfig"][nameof(EmailConfig.UserName)] = data.UserName;
            jsonObject["EmailConfig"][nameof(EmailConfig.Password)] = data.Password;
            jsonObject["EmailConfig"][nameof(EmailConfig.FromAddress)] = data.FromAddress;
            jsonObject["EmailConfig"][nameof(EmailConfig.mEnableSsl)] = data.mEnableSsl;
        }

        using var writer = new StreamWriter(filePath);
        using (JsonTextWriter jsonwriter = new JsonTextWriter(writer))
        {
            jsonObject.WriteTo(jsonwriter);
        }

        EmailConfigData = data;
    }
}


public class EmailConfig
{
    public string ServerHost { get; set; }
    public int ServerPort { get; set; }
    public bool mEnablePwdAuthentication { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public string FromAddress { get; set; }
    public bool mEnableSsl { get; set; }
}
GarsonZhang www.yesdotnet.com

Startup.cs 文件 Configure 方法中添加配置

// 加载配置
GlobalData.LoadData(Configuration);
GarsonZhang www.yesdotnet.com

添加加载配置方法

appsettings.json 配置

 "EmailConfig": {
    "ServerHost": "smtp.mxhichina.com",
    "ServerPort": 25,
    "mEnablePwdAuthentication": true,
    "UserName": "***@***.com",
    "Password": "***",
    "FromAddress": "***@***.com",
    "mEnableSsl": false
  }

appsetting.json 配置

测试

public class SubmitModel
{
    public string email { get; set; }
}
public IActionResult submit(SubmitModel model)
{
    Libs.EmailProvider emailProvider = new Libs.EmailProvider();
    var data = emailProvider.sendEmail(model.email, "测试邮件", "这是一条测试信息");
    return APISuccess("保存成功", null);
}
GarsonZhang www.yesdotnet.com

测试邮件

 

遇到问题

阿里云邮箱

使用阿里云邮箱发送邮件时,如果发送邮件遇到报错问题,参考: https://www.yesdotnet.com/archive/post/1627995781.html 

 

 

版权声明:本文为YES开发框架网发布内容,转载请附上原文出处连接
YES开发框架
上一篇:C#图片处理
评论列表

发表评论

评论内容
昵称:
关联文章

C#邮件发送
C# 邮件发送,阿里云邮箱参数设置,邮件发送测试工具下载
消息发送时的问题
客户端发送数据
客户端发送,服务端接收并输出
vue项目使用axios发送请求让ajax请求头部携带cookie
解决 axios 跨域时,发送 post 请求前options 404
C# Socket网络编程 系列课程
C#的进化——C#发展史、C#1.0-10.0语法系统性梳理、C#与JAVA的对比
C#代码编码规范手册 软件开发规范 开发指南
C#使用默认浏览器打开URL
.NET C#教程初级篇 1-1 基本数据类型及其存储方式
C# HTTP或HTTPS Get请求 和 Post 请求
C# SQLServer数据库连接
C# List排序
C# 指针简单使用
C#加密:SHA1
C# 数据库连接字符串Microsoft.Data.Sqlite数据库连接
C# 执行Javascript脚本
C#中URL编码