ccruiの博客

ccruiの博客

邮件HTML模板 附.net邮件发送方法

76
2023-04-18

邮件效果

邮件效果

邮件模板

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{Subject}}</title>
</head>

<body style="margin: 0; padding: 0; font-family: 'Arial', sans-serif; background-color: #f4f4f4;">
    <table align="center" border="0" cellpadding="0" cellspacing="0" width="600" style="border-collapse: collapse;">
        <tr>
            <td bgcolor="#ffffff">
                <img src="{{imageUrl}}" alt="image" width="100%" style="display: block;" />
            </td>
        </tr>
        <tr>
            <td align="center" bgcolor="#ffffff"
                style="padding: 20px 0 20px 0; font-size: 28px; font-weight: bold; color: #333333;">
                {{projectName}}
            </td>
        </tr>
        <tr>
            <td bgcolor="#ffffff" style="padding: 20px;">
                <table border="0" cellpadding="0" cellspacing="0" width="100%">
                    <tr>
                        <td style="color: #333333; font-size: 18px;">
                            <b>亲爱的 {{UserName}},</b>
                        </td>
                    </tr>
                    <tr>
                        <td style="padding: 20px 0 30px 0; color: #666666; font-size: 16px; line-height: 20px;">
                            {{content}}
                        </td>
                    </tr>
                    <tr>
                        <td style="padding: 30px 0 0 0; color: #666666; font-size: 16px; line-height: 20px;">
                            {{information}}
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
        <tr>
            <td bgcolor="#ffffff" style="padding: 20px; color: #666666; font-size: 14px;">
                <table border="0" cellpadding="0" cellspacing="0" width="100%">
                    <tr>
                        <td width="75%" align="center">
                            {{footnote}}
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</body>

</html>

C#方法

解析方法

using System.Text.RegularExpressions;

public static class TemplateReplacer
{
    public static string ReplacePlaceholders(Dictionary<string, string> placeholders)
    {
        string template = System.IO.File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "EmailTemplate.html"));
        foreach (var placeholder in placeholders)
        {
            string pattern = $"{{{{{placeholder.Key}}}}}";
            template = Regex.Replace(template, pattern, placeholder.Value);
        }

        return template;
    }
}

使用方法

        string emailBody = TemplateReplacer.ReplacePlaceholders(new Dictionary<string, string>()
        {
            { "Subject", "AICHAT验证码" },
            { "imageUrl", "https://img-cdn.ccrui.cn/2023/04/18/v2-0768f34e8784f31dbbf1be10118e33a6_r.jpg" },
            { "projectName", "AICHAT" },
            { "UserName", "用户" },
            { "content", $"您的验证码为{code},请在10分钟内使用" },
            { "information", "如有任何疑问或需要进一步的信息,请随时联系我们。<br><br>期待为您提供更多的帮助!" },
            { "footnote", "© 2023 All rights reserved" }
        });

邮件发送方法

using System.Net;
using System.Net.Mail;

namespace ChatGPT_API.Tool;

public class SMTPMail
{
    private readonly MailConfiguration _mailConfiguration; //SMTP服务器

    public SMTPMail(MailConfiguration mailConfiguration)
    {
        _mailConfiguration = mailConfiguration;
    }

    public bool Send()
    {
        try
        {
            //确定smtp服务器地址 实例化一个Smtp客户端
            SmtpClient smtpclient = new SmtpClient();
            smtpclient.Host = _mailConfiguration.smtpService;
            smtpclient.Port = _mailConfiguration.port; //qq邮箱可以不用端口

            //确定发件地址与收件地址
            MailAddress sendAddress = new MailAddress(_mailConfiguration.sendEmail, "AICHAT");
            MailAddress receiveAddress = new MailAddress(_mailConfiguration.reAddress);

            //构造一个Email的Message对象 内容信息
            MailMessage mailMessage = new MailMessage(sendAddress, receiveAddress);
            mailMessage.Subject = _mailConfiguration.subject;
            mailMessage.SubjectEncoding = System.Text.Encoding.UTF8;
            mailMessage.Body = _mailConfiguration.body;
            mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
            mailMessage.IsBodyHtml = true;

            //邮件发送方式  通过网络发送到smtp服务器
            smtpclient.DeliveryMethod = SmtpDeliveryMethod.Network;

            //如果服务器支持安全连接,则将安全连接设为true
            smtpclient.EnableSsl = true;
            try
            {
                //是否使用默认凭据,若为false,则使用自定义的证书,就是下面的networkCredential实例对象
                smtpclient.UseDefaultCredentials = false;

                //指定邮箱账号和密码,需要注意的是,这个密码是你在QQ邮箱设置里开启服务的时候给你的那个授权码
                NetworkCredential networkCredential =
                    new NetworkCredential(_mailConfiguration.sendEmail, _mailConfiguration.sendPwd);
                smtpclient.Credentials = networkCredential;


                //发送邮件
                smtpclient.Send(mailMessage);
                return true;
            }
            catch (System.Net.Mail.SmtpException ex)
            {
                return false;
            }
        }
        catch (Exception e)
        {
            return false;
        }
    }
}

public class MailConfiguration
{
    /// <summary>
    /// SMTP服务器
    /// </summary>
    public string smtpService { get; set; }

    /// <summary>
    /// 发件人邮箱
    /// </summary>
    public string sendEmail { get; set; }

    /// <summary>
    /// SMTP密码
    /// </summary>
    public string sendPwd { get; set; }

    /// <summary>
    /// SMTP端口
    /// </summary>
    public int port { get; set; } = 587;

    /// <summary>
    /// 接收邮件的地址
    /// </summary>
    public string reAddress { get; set; }

    /// <summary>
    /// 邮件主题
    /// </summary>
    public string subject { get; set; }

    /// <summary>
    /// 邮件内容
    /// </summary>
    public string body { get; set; }
}