MVC中定时发布二维码邮件

发布邮件 查看第一个方法就可以了,第二个跟这个无关

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Data;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;
using System.Text;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Threading;
using LmsApiSample.Functions;
using LmsApiSample.Models;
using LmsApiSample.Areas.Models;
using LmsApiSample.DAL;
using ThoughtWorks;
using ThoughtWorks.QRCode;
using ThoughtWorks.QRCode.Codec;
using ThoughtWorks.QRCode.Codec.Data; namespace LmsApiSample.Areas.Training.Controllers
{
public class TrainingRelation
{
//定时任务发送邮件
public void SendTeacherEmail()
{
List<lmsTraining> TrainingList = GetTrainingListForSendEmail();
SendTeacherEmailRecordDAL dao = new SendTeacherEmailRecordDAL();
if (TrainingList.Count > )
{
foreach (var training in TrainingList)
{
List<lmsTeacher> TeacherList = GetTeacherListForSendEmail(training.TrainingID);
List<lmsUserInfo> UserList = GetUserInfoForSendEmail(training.TrainingID, training.IsApprove);
string content = GetTemplateByUserInfoForSendEmail(UserList);
string TrainingName = training.TrainingName;
string fileName = TrainingName + DateTime.Now.ToString("yyyyMMddHHmmssfff");
string path = AppDomain.CurrentDomain.BaseDirectory+"UpLoad\\QRCode\\" + fileName + ".png";
GenerateCode(training.TrainingID, path);
//发送邮件
foreach (var t in TeacherList)
{
DataTable dt = dao.GetList(" TrainingID=" + training.TrainingID + " and TeacherID=" + t.teacherID).Tables[];
if (dt == null || dt.Rows.Count == )
{
MailInfo mailInfo = new MailInfo
{
Receiver = t.Email,
ReceiverName = t.teacherName,
Subject = TrainingName + "培训邮件发送",
Body = content
};
SendMail.SendEmail(mailInfo, path, TrainingName + ".png");
SendTeacherEmailRecord record = new SendTeacherEmailRecord();
record.TeacherID = t.teacherID;
record.TrainingID = training.TrainingID;
record.Content = content;
record.UpdateTime = DateTime.Now;
record.CreateTime = DateTime.Now;
dao.Add(record); }
}
}
}
} //培训讲师编辑发送邮件
public void SendTeacherEmailByModify(int TrainingID)
{
lmsTrainingDAL tdao=new lmsTrainingDAL ();
lmsTraining training = tdao.GetModel(TrainingID); SendTeacherEmailRecordDAL dao = new SendTeacherEmailRecordDAL();
List<lmsTeacher> TeacherList = GetTeacherListForSendEmail(training.TrainingID);
List<lmsUserInfo> UserList = GetUserInfoForSendEmail(training.TrainingID, training.IsApprove);
string content = GetTemplateByUserInfoForSendEmail(UserList);
string TrainingName = training.TrainingName;
string fileName = TrainingName + DateTime.Now.ToString("yyyyMMddHHmmssfff");
string path = System.Web.HttpContext.Current.Server.MapPath("~/UpLoad/QRCode/").ToString() + fileName + ".png";
GenerateCode(training.TrainingID, path);
//发送邮件
foreach (var t in TeacherList)
{
DataTable dt = dao.GetList(" TrainingID=" + training.TrainingID + " and TeacherID=" + t.teacherID).Tables[];
if (dt == null || dt.Rows.Count == )
{
MailInfo mailInfo = new MailInfo
{ Receiver = t.Email,
ReceiverName = t.teacherName,
Subject = TrainingName + "培训邮件发送",
Body = content
};
SendMail.SendEmail(mailInfo, path, TrainingName+".png");
SendTeacherEmailRecord record = new SendTeacherEmailRecord();
record.TeacherID = t.teacherID;
record.TrainingID = training.TrainingID;
record.Content = content;
record.UpdateTime = DateTime.Now;
record.CreateTime = DateTime.Now;
dao.Add(record); }
}
} public List<lmsTraining> GetTrainingListForSendEmail()
{
List<lmsTraining> list = new List<lmsTraining>();
lmsTrainingDAL dao = new lmsTrainingDAL();
DataTable dt = dao.GetList(" cast(convert(varchar(100),dateadd(day,-1,TrainingStartTime),12) as varchar(100))=convert(varchar(100),getdate(),12)").Tables[];
for (var i = ; i < dt.Rows.Count; i++)
{
lmsTraining model = dao.DataRowToModel(dt.Rows[i]);
list.Add(model);
}
return list;
} public List<lmsTeacher> GetTeacherListForSendEmail(int TrainingID)
{
List<lmsTeacher> list = new List<lmsTeacher>();
lmsTeacherDAL dao = new lmsTeacherDAL();
DataTable dt = dao.GetList(" teacherID in (select TeacherID from TrainingTeacherRelation where TrainingID=" + TrainingID + ") ").Tables[];
for (var i = ; i < dt.Rows.Count; i++)
{
lmsTeacher model = dao.DataRowToModel(dt.Rows[i]);
list.Add(model);
}
return list;
} public List<lmsUserInfo> GetUserInfoForSendEmail(int TrainingID, bool IsApprove)
{
List<lmsUserInfo> list = new List<lmsUserInfo>();
lmsUserInfoDAL dao = new lmsUserInfoDAL();
string condition = string.Empty;
if (IsApprove)
{
condition += " and State=1";
}
DataTable dt = dao.GetList(" user_id in (select UserID from lmsEnrolling where IsCancel=0 and TrainingID=" + TrainingID + condition + ")").Tables[];
for (var i = ; i < dt.Rows.Count; i++)
{
lmsUserInfo model = dao.DataRowToModel(dt.Rows[i]);
list.Add(model);
}
return list;
} public string GetTemplateByUserInfoForSendEmail(List<lmsUserInfo> list)
{ StringBuilder strBuilder = new StringBuilder();
lmsAreaInfoDAL dao = new lmsAreaInfoDAL();
if (list != null && list.Count > )
{ strBuilder.Append("<table>");
strBuilder.Append("<tr>");
strBuilder.Append("<th>经销商</th>");
strBuilder.Append("<th>姓名</th>");
strBuilder.Append("<th>PIN</th>");
strBuilder.Append("</tr>");
foreach (var l in list)
{
//lmsAreaInfo info = new lmsAreaInfo();
//DataTable dt = dao.GetList(" area_id=").Tables[0];
lmsAreaInfo info = dao.GetModel(Convert.ToInt32(l.user_area3_id));
if (info != null)
{
strBuilder.Append("<tr>");
strBuilder.Append("<td>" + info.area_name + "</td>");
strBuilder.Append("<td>" + l.user_name + "</td>");
strBuilder.Append("<td>" + l.login_name + "</td>");
strBuilder.Append("</tr>");
}
}
strBuilder.Append("<table>");
}
return strBuilder.ToString();
} #region 生成二维码链接
////Base64浏览图片 (浏览器不兼容)
//public string GenerateCode(int TrainingID)
//{
// try
// {
// string str = System.Configuration.ConfigurationManager.AppSettings["MobileDomain"] + "/lmsViews/wechat/index.html#/main/signIn?TrainingID=" + TrainingID;
// //初始化二维码生成工具
// QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
// qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
// qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
// qrCodeEncoder.QRCodeVersion = 0;
// qrCodeEncoder.QRCodeScale = 4;
// //将字符串生成二维码图片
// Bitmap image = qrCodeEncoder.Encode(str, Encoding.Default);
// //保存为PNG到内存流
// MemoryStream ms = new MemoryStream(); // image.Save(ms, ImageFormat.Png);
// string strUrl = "data:image/gif;base64," + Convert.ToBase64String(ms.ToArray());
// image.Dispose();
// ms.Dispose(); // return strUrl;
// }
// catch (Exception e)
// {
// ///修改为单例访问日志记录对象
// LogConcel.GetLogInstance.WriteExceptionLog(e, "Method:GenerateCode");
// return null;
// }
//} public void GenerateCode(int TrainingID, string path)
{
//删除同名的图片
//if (File.Exists(path))
//{
// Thread.Sleep(2000);
// File.Delete(path);
//}
//生成二维码
string str = System.Configuration.ConfigurationManager.AppSettings["MobileDomain"] + "/lmsViews/wechat/index.html#/main/signIn?TrainingID=" + TrainingID;
//初始化二维码生成工具
QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
qrCodeEncoder.QRCodeVersion = ;
qrCodeEncoder.QRCodeScale = ;
//将字符串生成二维码图片
Bitmap image = qrCodeEncoder.Encode(str, Encoding.Default);
image.Save(path, System.Drawing.Imaging.ImageFormat.Png);
image.Dispose();
} #endregion
}
}

Global.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing; namespace LmsApiSample
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
TimeTaskConfig.BeginTask();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
GlobalConfiguration.Configuration.EnableCors();
log4net.Config.XmlConfigurator.Configure();
GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("json", "true", "application/json"));
}
}
}

里面添加了TimeTaskConfig

TimeTaskConfig类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Timers;
using System.Threading;
using System.Threading.Tasks;
using LmsApiSample.Areas.Training.Controllers; namespace LmsApiSample
{
public class TimeTaskConfig
{ public static void BeginTask()
{
//定义定时器
//1000表示1秒的意思
System.Timers.Timer myTimer = new System.Timers.Timer(*);
//设置是执行一次(false)还是一直执行(true);
myTimer.AutoReset = true;
//是否执行System.Timers.Timer.Elapsed事件;
myTimer.Enabled = true;
//到达时间的时候执行事件(theout方法);
myTimer.Elapsed += new System.Timers.ElapsedEventHandler(ElapsedEvent);
} public static void ElapsedEvent(object source, System.Timers.ElapsedEventArgs e)
{
try
{
CallWithTimeout(WorkTask, **);
}
catch (Exception ex)
{
//
}
} public static void WorkTask()
{
//定时发送给讲师培训邮件
//每天九点的时间发送邮件
if (DateTime.Now.Hour == )
{
new TrainingRelation().SendTeacherEmail();
}
}
/// <summary>
///
/// </summary>
/// <param name="action">任务</param>
/// <param name="timeoutMilliseconds">多长时间回收线程</param>
public static void CallWithTimeout(Action action, int timeoutMilliseconds)
{
Thread threadToKill = null;
Action wrappedAction = () =>
{
threadToKill = Thread.CurrentThread;
action();
}; IAsyncResult result = wrappedAction.BeginInvoke(null, null);
if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds))
{
wrappedAction.EndInvoke(result);
}
else
{
threadToKill.Abort();
//LogHelper.Error(typeof(ImportAttendanceData), "超时抛出");
//throw new TimeoutException();
}
}
} }

上面用到的上传邮件的类

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Net;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net.Mime;
using System.IO;
using System.Timers;
using System.Xml; namespace LmsApiSample.Functions
{
/// <summary>
/// 发送邮件的信息
/// </summary>
public class MailInfo
{
/// <summary>
/// 主题行
/// </summary>
private string _subject; /// <summary>
/// 接收者名字
/// </summary>
public string ReceiverName { get; set; } /// <summary>
/// 接收者邮箱(多个用英文“,”号分割)
/// </summary>
public string Receiver { get; set; } /// <summary>
/// 邮件的主题行
/// </summary>
public string Subject
{
get
{
if (string.IsNullOrEmpty(_subject) && _subject.Length > )
{
return Body.Substring(, );
}
return _subject;
}
set { _subject = value; }
} /// <summary>
/// 正文内容
/// </summary>
public string Body { get; set; } /// <summary>
/// 抄送人集合
/// </summary>
public string CC { get; set; } /// <summary>
/// 回复地址
/// </summary>
public string Replay { get; set; }
}
/// <summary>
/// 邮件配置信息
/// </summary>
//[JsonObject]
public class MailConfig
{
private string _path = string.Empty; /// <summary>
/// 主机名 如:smtp.163.com
/// </summary>
//[JsonProperty]
public string Host { get; set; } /// <summary>
/// 端口号 如:25
/// </summary>
//[JsonProperty]
public int Port { get; set; } /// <summary>
/// 用户名
/// </summary>
//[JsonProperty]
public string User { get; set; } /// <summary>
/// 密码
/// </summary>
//[JsonProperty]
public string Password { get; set; } /// <summary>
/// 是否包含Html代码
/// </summary>
//[JsonProperty]
public bool IsHtml { get; set; } /// <summary>
/// 发送者显示名
/// </summary>
//[JsonProperty]
public string DisplayName { get; set; } /// <summary>
/// 来源
/// </summary>
//[JsonProperty]
public string From { get; set; } /// <summary>
/// 是否启用SSL 默认:false
/// 如果启用 端口号要改为加密方式发送的
/// </summary>
//[JsonProperty]
public bool EnableSsl { get; set; }
} /// <summary>
/// 发送邮件
/// </summary>
public class SundayMail
{
private static MailConfig mailConfig; /// <summary>
/// 使用指定的 Mafly.Mail.Config 类对象初始化 Mafly.Mail 类的新实例。
/// </summary>
/// <param name="config">包含邮件配置信息的 Mafly.Mail.Config。</param>
public SundayMail(MailConfig config)
{
mailConfig = config;
} /// <summary>
/// 发送邮件
/// </summary>
/// <param name="receiver">接收人邮箱</param>
/// <param name="body">邮件内容</param>
public void Send(string receiver, string body)
{
Send(new MailInfo { Receiver = receiver, ReceiverName = receiver, Body = body, Subject = body });
} /// <summary>
/// 发送邮件
/// </summary>
/// <param name="receiver">接收人邮箱</param>
/// <param name="receiverName">接收人姓名</param>
/// <param name="body">邮件内容</param>
public void Send(string receiver, string receiverName, string body)
{
Send(new MailInfo { Receiver = receiver, ReceiverName = receiverName, Body = body, Subject = body });
} /// <summary>
/// 发送邮件
/// </summary>
/// <param name="receiver">接收人邮箱</param>
/// <param name="receiverName">接收人姓名</param>
/// <param name="subject">邮件主题</param>
/// <param name="body">邮件内容</param>
public void Send(string receiver, string receiverName, string subject, string body)
{
Send(new MailInfo { Receiver = receiver, ReceiverName = receiverName, Body = body, Subject = subject });
} /// <summary>
/// 发送邮件
/// </summary>
/// <param name="info">接收人信息 Mafly.Mail.MailInfo </param>
/// <param name="message">默认为null。 System.Net.Mail.MailMessage </param>
public void Send(MailInfo info, MailMessage message = null)
{
var sender = new SmtpClient();
message = message ?? new MailMessage();
if (string.IsNullOrEmpty(info.ReceiverName))
info.ReceiverName = info.Receiver;
if (info.Receiver.Contains(","))
message.To.Add(info.Receiver);
else
message.To.Add(new MailAddress(info.Receiver, info.ReceiverName)); message.Subject = info.Subject;
if (!string.IsNullOrEmpty(info.Replay))
message.ReplyToList.Add(new MailAddress(info.Replay));
message.Body = info.Body;
if (!string.IsNullOrEmpty(info.CC))
message.CC.Add(new MailAddress(info.CC));
try
{
message.IsBodyHtml = mailConfig.IsHtml;
message.From = new MailAddress(mailConfig.From, mailConfig.DisplayName);
sender.Host = mailConfig.Host;
sender.Port = mailConfig.Port;
sender.UseDefaultCredentials = false;
sender.Credentials = new NetworkCredential(mailConfig.User, mailConfig.Password);
sender.DeliveryMethod = SmtpDeliveryMethod.Network;
sender.EnableSsl = mailConfig.EnableSsl;
sender.Send(message);
}
catch (Exception ex)
{
message.From = new MailAddress("NuGets@163.com", "NuGet_Mafly");
message.IsBodyHtml = true;
sender.Host = "smtp.163.com";
sender.Port = ;
sender.UseDefaultCredentials = false;
sender.Credentials = new NetworkCredential("NuGets@163.com", "vzihlbquwnriqlht");
sender.DeliveryMethod = SmtpDeliveryMethod.Network;
sender.EnableSsl = false;
sender.Send(message);
//throw new Team.Common.Exceptions.EmailConfigurationException { Status = Team.Common.Enums.EmailConfiguration.ConfigurationError };
}
// sender.Send(message);
} /// <summary>
/// 发送邮件(带附件)
/// </summary>
/// <param name="info">接收人信息 Mafly.Mail.MailInfo </param>
/// <param name="attachments">附件列表 System.Net.Mail.Attachment </param>
public void Send(MailInfo info, params Attachment[] attachments)
{
var message = new MailMessage();
foreach (var item in attachments)
{
message.Attachments.Add(item);
}
try
{
Send(info, message);
}
catch (Exception e)
{
throw e;
}
} /// <summary>
/// 发送邮件(带附件)
/// </summary>
/// <param name="info">接收人信息 Mafly.Mail.MailInfo </param>
/// <param name="filePath">附件路径 System.String </param>
public void Send(MailInfo info, string filePath)
{
var message = new MailMessage();
message.Attachments.Add(new Attachment(filePath));
Send(info, message);
}
} public class SendMail
{
private static string emailAccount = ConfigurationManager.AppSettings["emailAccount"];
private static string emailPass = ConfigurationManager.AppSettings["emailPassword"];
private static string emailDisplyName = ConfigurationManager.AppSettings["emailDisplyName"];
private static string smtp = ConfigurationManager.AppSettings["smtp"]; private static SundayMail mailservice;
static SendMail()
{
MailConfig config = new MailConfig
{
IsHtml = true,
Port = ,
User = emailAccount,
Password = emailPass,
EnableSsl = false,
From = emailAccount,
DisplayName = emailDisplyName,
Host = smtp };
mailservice = new SundayMail(config);
} public static void SendEmail(MailInfo mailInfo)
{ mailservice.Send(mailInfo);
} public static void SendEmail (MailInfo mailInfo,string path,string name)
{
Attachment attachment = new Attachment(path);
attachment.Name=name;
mailservice.Send(mailInfo, attachment);
}
}
}

需要注意的

在TimeTaskConfig中有个生成二维码注释掉的,用base64方式上传图片,在edge,猎豹浏览器中可以,在谷歌,火狐中不行,最后用了上传附件。

在Global中获取文件夹路径,不能使用Server.MapPath

网上查询现在有两种方式

AppDomain.CurrentDomain.BaseDirectory

HttpRuntime.AppDomainAppPath

Environment.CurrentDirectory

MVC中定时发布二维码邮件

第3个为什么是c盘???

这个路径就是配置iis网站的路径

MVC中定时发布二维码邮件

调试Global时,除了 要重新启动iis中的网站以外,还要重新加载该网站的任何一个页面。

上一篇:解决linux系统CentOS下调整home和根分区大小


下一篇:Apache Solr采用Java开发、基于Lucene的全文搜索服务器