C# 发送邮件,MimeMessage 配置

思路    

 发送邮件一般得有一个发送的账户信息,我理解的就是个载体。其次发送内容,最后目标人群。

1.邮箱配置SMTP

   登录邮箱---设置---账户设置---开启SMTP服务(记住授权码) 至于更详细的教程百度搜索

2.下面是发送的方法,这几个参数啥意思

 /// <summary> /// 同步发送邮件 /// </summary> /// <param name="host">主机--QQ邮箱默认smtp.qq.com</param> /// <param name="port">端口--QQ邮箱默认465</param> /// <param name="account">账号 --邮箱地址发件人</param> /// <param name="password">密码 --第一步获取的授权码</param> /// <param name="message">邮件模型</param> /// <returns></returns> public static Exception Send(string host, int port, string account, string password, MimeMessage message) { try { using (var client = new SmtpClient()) { client.Timeout = 5000; client.Connect(host, port, true); client.Authenticate(account, password); client.Send(message); client.Disconnect(true); } return null; } catch (Exception e) { return e; } }
MimeMessage 的配置

 public async Task Emailadd (Guid? id, ERPMarketingEmail Email, List<ERPMarketingCustomer> customlist, AppSettings appSettingService, Guid UserID) { using (var scope = _serviceScopeFactory.CreateScope()) { var dbContext = scope.ServiceProvider.GetService<UnitemillManageDbContext>(); MimeMessage message = new MimeMessage();//实例化对象 message.From.Add(new MailboxAddress(Encoding.UTF8, appSettingService.DisplayName, appSettingService.From));//配置邮件的显示名称和发送账户 if (Email != null) { message.Subject = Email.Title;//邮件的标题 var bodyBuilder = new BodyBuilder(); bodyBuilder.HtmlBody = Email.Text; message.Body = bodyBuilder.ToMessageBody();//这是邮件的内容,通过BodyBuilder将text文本转换成HTML的body,并且赋值给body } if (customlist.Count > 0) { foreach (var oneCustom in customlist) { message.Bcc.Clear(); message.To.Clear(); if (appSettingService.IsBCC)//这个位置是验证接收客户的邮箱是不是隐匿发送(不确定往to里加就行) { message.Bcc.Add(new MailboxAddress(oneCustom.Email));
 }
else { message.To.Add(new MailboxAddress(oneCustom.Email));//message.to 可以继续添加,我这里是考虑到服务器的压力所以一个客户发一次 } int r = new Random().Next(10, 45); System.Threading.Thread.Sleep(r * 1000); Email.CreateDate = DateTime.Now; Email.CreateUserId = UserID; var ex = SMTPHelper.Send(appSettingService.Host, appSettingService.Port, appSettingService.UserName, appSettingService.Password, message);
//调用上面的方法执行发送操作,发送完成记得数据库加一行记录啊如下
if (ex == null) { 成功,添加日志 } else { 失败,添加日志 } } } } }

 



 

 public static Exception Send(string host, int port, string account, string password, MimeMessage message)        {            try            {                using (var client = new SmtpClient())                {                    client.Timeout = 5000;                    client.Connect(host, port, true);                    client.Authenticate(account, password);
                    client.Send(message);
                    client.Disconnect(true);                }
                return null;            }            catch (Exception e)            {                return e;            }        }

相关文章