C#邮件发送

应用场景:系统找回密码,严重码发送邮箱,或者预警信息发送通知者邮箱,并做日志记录
图片.png

公共类:EmailHelper

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Text;
using DataAccess;

namespace Helper
{
    public class EmailHelper
    {
        public static readonly string m_Facility = ConfigurationManager.AppSettings["FACILITY"];
        public static readonly string m_Site = ConfigurationManager.AppSettings["SITE"];
        public static readonly string m_ConnStr = ConfigurationManager.ConnectionStrings["iROCKDbString"].ConnectionString;
        public static bool SendEmail(bool enableSsl, string nickName, string toMail, string subj, string bodys,List<string> attachmentFileName = null)
        {
            var result = false;
            string smtpserver = string.Empty, userName = string.Empty, pwd = string.Empty;

            GetEmailServerDetail(m_Facility, m_Site, out smtpserver, out userName, out pwd);

            SmtpClient smtpClient = new SmtpClient();

            smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;//指定电子邮件发送方式

            smtpClient.Host = smtpserver;//指定SMTP服务器

            smtpClient.Credentials = new NetworkCredential(userName, pwd);//用户名和密码

            smtpClient.EnableSsl = enableSsl;

            MailAddress fromAddress = new MailAddress(userName, nickName);

            MailAddress toAddress = new MailAddress(toMail);

            MailMessage mailMessage = new MailMessage(fromAddress, toAddress);

            if (attachmentFileName!=null&&attachmentFileName.Count>0)
            {
                foreach (var att in attachmentFileName)
                {
                    Attachment objFile = new System.Net.Mail.Attachment(att);
                    objFile.Name = Path.GetFileName(att);
                    mailMessage.Attachments.Add(objFile);
                }
              
            } 

            mailMessage.Subject = subj;//主题
           
            mailMessage.Body = bodys;//内容

            mailMessage.BodyEncoding = Encoding.Default;//正文编码

            mailMessage.IsBodyHtml = true;//设置为HTML格式

            mailMessage.Priority = MailPriority.Normal;//优先级

            smtpClient.Send(mailMessage);
            result = true;

            return result;
        }

        public static bool SendEmail(bool enableSsl, string nickName, List<string> toMails, string subj, string bodys, List<string> attachmentFileName = null)
        {
            var result = false;
            string smtpserver = string.Empty, userName = string.Empty, pwd = string.Empty;

            GetEmailServerDetail(m_Facility, m_Site, out smtpserver, out userName, out pwd);

            SmtpClient smtpClient = new SmtpClient();

            smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;//指定电子邮件发送方式

            smtpClient.Host = smtpserver;//指定SMTP服务器

            smtpClient.Credentials = new NetworkCredential(userName, pwd);//用户名和密码

            smtpClient.EnableSsl = enableSsl;

            MailAddress fromAddress = new MailAddress(userName, nickName);

            MailMessage mailMessage = new MailMessage();

            mailMessage.From = fromAddress;

            toMails.ForEach(p =>
            {
                if (!string.IsNullOrEmpty(p))
                {
                    MailAddress mailAddress = new MailAddress(p);
                    mailMessage.To.Add(mailAddress);
                }
            });

            if (attachmentFileName != null && attachmentFileName.Count > 0)
            {
                foreach (var att in attachmentFileName)
                {
                    Attachment objFile = new System.Net.Mail.Attachment(att);
                    objFile.Name = Path.GetFileName(att);
                    mailMessage.Attachments.Add(objFile);
                }

            }

            mailMessage.Subject = subj;//主题

            mailMessage.Body = bodys;//内容

            mailMessage.BodyEncoding = Encoding.Default;//正文编码

            mailMessage.IsBodyHtml = true;//设置为HTML格式

            mailMessage.Priority = MailPriority.Normal;//优先级

            smtpClient.Send(mailMessage);
            result = true;

            return result;
        }

        private static void GetEmailServerDetail(string facility, string site, out string smtpserver, out string userName, out string pwd)
        {
            smtpserver = string.Empty;
            userName = string.Empty;
            pwd = string.Empty;
            SqlDataAccess dataAccess = new SqlDataAccess(m_ConnStr);
            DataTable systemAttribute = dataAccess.ExecuteDataSet("Select * from SY_S_LOOKUP where table_name='SY_SYSTEM_ATTRIBUTE' and ALPHA1='ALARM'").Tables[0];
            //var systemAttribute = m_LookUpRepository.GetLookUpRecordByField(facility, site, "SY_SYSTEM_ATTRIBUTE", "ALARM");
            if (systemAttribute != null && systemAttribute.Rows.Count > 0)
            {
              
                smtpserver = systemAttribute.Select("Alpha2='STMP'")[0]["Alpha3"].ToString() ;
               
                userName = systemAttribute.Select("Alpha2='USERNAME'")[0]["Alpha3"].ToString();

                pwd = systemAttribute.Select("Alpha2='PASSWORD'")[0]["Alpha3"].ToString();
              
            }
            else
            {
               throw new Exception("未配置发送邮件服务器信息");
            }
        }
    }
}

config 配置

  <connectionStrings>
    <add name="iROCKDbString" connectionString="Data Source=192.168.0.000; Initial Catalog=库名;User ID=账号;Password=密码;Connect Timeout=1800" />
    <add name="TestDbString"  connectionString="Data Source=192.168.0.000; Initial Catalog=库名;User ID=账号;Password=密码;Connect Timeout=1800" />
    <add name="ActiveDbString"  connectionString="Data Source=192.168.0.000; Initial Catalog=库名;User ID=账号;Password=密码;Connect Timeout=1800" />
  </connectionStrings>

 方法GetEmailServerDetail 取出的账号密码

发送邮件携带附件(如压缩包,文档)

//nickName 		发送人的 抬头 名称
//toMail    	接收人的邮箱
//subj      	收件人的名称
//bodys     	邮件的主体内容  html 格式
//dataPath      附件的地址(物理路径)
//dataFolder	附件名称

//单个收件人
private bool SendFileUseEmail(string nickName, string toMail, string subj, string bodys, string dataPath, string dataFolder)
{
	List<string> attachmentFiles = new List<string>();
	if (Directory.Exists(dataPath + dataFolder))
	{
		DirectoryInfo dir = new DirectoryInfo(dataPath + dataFolder);
		foreach (var file in dir.GetFiles())
		{
			attachmentFiles.Add(file.FullName);
		}
	}
	return EmailHelper.SendEmail(false, nickName, toMail, subj, bodys, attachmentFiles);
}

//多个收件人
private bool SendFileUseEmails(string nickName, string toMail, string subj, string bodys, string dataPath, string dataFolder)
{
	List<string> attachmentFiles = new List<string>();
	if (Directory.Exists(dataPath + dataFolder))
	{
		DirectoryInfo dir = new DirectoryInfo(dataPath + dataFolder);
		foreach (var file in dir.GetFiles())
		{
			attachmentFiles.Add(file.FullName);
		}
	}
	return EmailHelper.SendEmail(false, nickName, toMail.Split(';').ToList(), subj, bodys, attachmentFiles);
}

邮件主体内容 bodys

private string BulidEDTEmailBody(string salesOrder, string prod, string oqcNo)
{
	StringBuilder emailBody = new StringBuilder();
	emailBody.Append("<head><style type='text/css'>.margin {margin-left:20px;color:#000;font-size:16px;}.name {vertical-align:top;float:right;font-weight:bold;padding-left:15px;}</style></head>");
	emailBody.Append("<div style=\"color:#000;font-size:18px;\">");
	emailBody.AppendFormat("<p>Hi ALL:</p>");
	emailBody.Append("<p class=\"margin\">" + String.Format("销售订单号:{0}\r\n品号:{1}\r\n送检单号:{2}\r\n对应的数据EDT已生成成功,请参阅附件。", salesOrder, prod, oqcNo) + "</p>");
	emailBody.Append("<br />");
	//emailBody.Append("<p class=\"margin\">这是MES系统电子邮件,无需回复!</p>");
	return emailBody.ToString();
}

不携带附件发送

[HttpPost]
public bool SendEmailAlertErpOrAgent(AccountApplyInfo employeeList, string alertType)
{
	var result = false;
	try
	{
		if (employeeList != null && employeeList.EmailAddress != null)
		{
			var body = BulidEmailBody(employeeList, alertType);
			var toMail = employeeList.EmailAddress;
			result = m_EmailService.SendEmail(Facility, Site, false, "iROCK System", toMail, string.Format(Label.AccountStatus, employeeList.EmpName), body);
		}
		return result;
		//return MessageJsonResult(result, result ? Message.SendEmailSuccess : Message.SendEmailFailed);
	}
	catch (Exception ex)
	{
		return false;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值