C# SmtpClient 发邮件

本文介绍了一个使用C#实现的异步邮件发送功能,通过定时任务定期发送邮件,并在本地记录详细的日志信息。示例代码展示了如何配置SMTP服务器,设置邮件内容,以及使用UTF8编码和异步发送方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Mail;
using System.Net; 
using System.Threading;
using System.IO;
using System.Security.Cryptography;

namespace ConsoleApp348
{
    class Program
    {        
        static string logFullPath = Directory.GetCurrentDirectory() + "\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt";
        static void Main(string[] args)
        {
            Timer emailTimer = new Timer(SendMailCallBack, null, 0, 1);
            Console.ReadLine();
        }
        
        private static void SendMailCallBack(object state)
        {
            string fromMail = "fromMail";
            string fromMailPwd = "fromMailPwd";
            string toMail = "toMail";
            MailExample(fromMail, fromMailPwd, toMail);
        }

        static void MailExample(string fromEmail, string fromEmailPwd, string toEmail)
        {            
            try
            {
                using (SmtpClient smtpClient = new SmtpClient())
                {
                    smtpClient.Host = "smtp.163.com";
                    smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                    smtpClient.UseDefaultCredentials = false;
                    smtpClient.Credentials = new System.Net.NetworkCredential(fromEmail, fromEmailPwd);
                    using (MailMessage mail = new MailMessage())
                    {
                        mail.BodyEncoding = UTF8Encoding.UTF8;
                        mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
                        mail.From = new MailAddress(fromEmail);
                        mail.To.Add(new MailAddress(toEmail));
                        mail.Subject = $"This is the new test.Now is {DateTime.Now.ToString("mmssffff")}";
                        mail.Body = $"This is the mail body,And now is {DateTime.Now.ToString("yyyyMMddHHmmssffff")}";
                        smtpClient.SendAsync(mail, $"Frommail:{fromEmail},ToMail:{toEmail},send email successfully!");
                        smtpClient.SendCompleted += SmtpClient_SendCompleted;
                    }                        
                }                    
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
                LogMessage(ex.StackTrace);
            }
        }

        private static void SmtpClient_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            Console.WriteLine(e.UserState);
            LogMessage(e.UserState.ToString());
        }

        static void LogMessage(string msg)
        {            
            lock(logFullPath)
            {
                using (StreamWriter logWriterStream = new StreamWriter(logFullPath, true, UTF8Encoding.UTF8))
                {
                    logWriterStream.WriteLine($"Log message :{msg},now is {DateTime.Now.ToString("yyyyMMddHHmmssffff")}");
                }
            }           
        }
    }
}

 异步:public void SendAsync(MailMessage message, object userToken);

Sends the specified e-mail message to an SMTP server for delivery. This method  does not block the calling thread and allows the caller to pass an object to  the method that is invoked when the operation completes.

转载于:https://www.cnblogs.com/Fred1987/p/10903419.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值