c# smtpclient发送邮件

using Microsoft.Extensions.Configuration;
using Serilog;
using System;
using System.Net;
using System.Net.Mail;
using System.Threading;

namespace SMTP
{
    public static class Mailer
    {
        private static readonly SmtpClient smtpClient;
        private static readonly Mutex mailerMutex = new();
        private static readonly string mailPassword;
        private static readonly string mailUser;
        private static readonly string mailServer;
        private static readonly int mailPort;
        private static readonly bool enableSsl;
        private static readonly string smtpFromEmail;
        private static readonly bool smtpRedirect;
        private static readonly string smtpRedirectEmail;
        private static readonly string bccEmail;
        private static readonly string ccEmail;
        private static readonly string serveDomainName;

        static Mailer()
        {
            var config = new ConfigurationBuilder()
                .SetBasePath(Environment.CurrentDirectory)
                .AddJsonFile("appsettings.json")
                .AddInMemoryCollection()
                .Build();
            mailPassword = config["Email:SmtpPass"];
            mailUser = config["Email:SmtpUser"];
            mailServer = config["Email:SmtpServer"];
            mailPort = Convert.ToInt32(config["Email:SmtpPort"]);
            enableSsl = config["Email:EnableSsl"] != null && Convert.ToBoolean(config["Email:EnableSsl"]);
            smtpFromEmail = config["Email:SmtpFromEmail"];
            smtpRedirect = config["Email:SmtpRedirect"] != null && Convert.ToBoolean(config["Email:SmtpRedirect"]);
            smtpRedirectEmail = config["Email:SmtpRedirectEmail"];
            bccEmail = config["Email:BCCEmail"];
            ccEmail = config["Email:CCEmail"];
            serveDomainName = config["Email:ServerDomainName"];
            smtpClient = new SmtpClient(mailServer, mailPort)
            {
                DeliveryMethod = SmtpDeliveryMethod.Network
            };
            if (string.IsNullOrEmpty(mailPassword))
                smtpClient.UseDefaultCredentials = false;
            else
            {
                smtpClient.UseDefaultCredentials = true;
                smtpClient.Credentials = new NetworkCredential(mailUser, mailPassword);
                smtpClient.EnableSsl = enableSsl;
            }
        }
        public static bool SendMessage(string recipients, string bcc, string cc, string subject, string body)
        {
            //get mutex
            mailerMutex.WaitOne();
            bool isSent = false;
            Log.Debug("Mailer.SendMessage: ready to send email");
            Log.Debug("Mailer.SendMessage:Send email to " + recipients);
            string from = smtpFromEmail;
            if (string.IsNullOrEmpty(from))
            {
                Log.Error("No email from address");
                return isSent;
            }
            MailMessage mailMessage = new();
            try
            {
                mailMessage.From = new MailAddress(from);
                if (string.IsNullOrEmpty(recipients))
                {
                    Log.Error("No email recipient address");
                    return isSent;
                }
                string emailto = recipients;
                if (smtpRedirect)
                {
                    emailto = smtpRedirectEmail;
                    Log.Debug("Redirected to " + emailto);
                    bcc = bccEmail;
                    cc = ccEmail;
                }
                if (string.IsNullOrEmpty(emailto))
                {
                    Log.Error("No email to address ");
                    return isSent;
                }
                string[] redirectEmailList = emailto.Split(';');
                foreach (string toAddress in redirectEmailList)
                {
                    mailMessage.To.Add(toAddress);
                }
                //Check if the bcc value is nothing or an empty string
                if (!string.IsNullOrEmpty(bcc))
                {
                    string[] bccList = bcc.Split(';');
                    foreach (string bccAddress in bccList)
                    {
                        if (!string.IsNullOrEmpty(bccAddress))
                            mailMessage.Bcc.Add(bccAddress);
                    }
                }
                //Check if the cc value is nothing or an empty string
                if (!string.IsNullOrEmpty(cc))
                {
                    string[] ccList = cc.Split(';');
                    foreach (string ccAddress in ccList)
                    {
                        if (!string.IsNullOrEmpty(ccAddress))
                            mailMessage.CC.Add(ccAddress);
                    }
                }
                string ServerDomain = serveDomainName;
                if (!string.IsNullOrEmpty(ServerDomain))
                {
                    mailMessage.Subject = subject + " - " + ServerDomain;
                }
                else
                {
                    //Set the subject of the mail message
                    mailMessage.Subject = subject;
                }
                mailMessage.Body = body;
                mailMessage.IsBodyHtml = true;
                mailMessage.Priority = MailPriority.Normal;
                Log.Debug("Mailer.SendMessage: begin...");
                smtpClient.Send(mailMessage);
                Log.Debug("Mailer.SendMessage-email body is " + body + ", email send successfully");
                isSent = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                mailMessage.Dispose();
                // Release the Mutex.              
                mailerMutex.ReleaseMutex();
            }
            return isSent;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值