ASP.NET MVC 生成EML文件
需求: 点发送邮件按钮的时候, 自动在客户端电脑打开默认邮件的窗口,并且把内容和附件都附加上去.
解决方案: 尝试使用过Microsoft.Office.Interop.Outlook 和 MPAI.dll 都无法实现, 在本地debug的时候是完全没问题的, 但是部署到IIS上后发现 这两个方式都会在服务器上寻找默认的邮件客户端. 显然这个不能实现的。
Mailto :方法可行, 也可以打开默认的邮件客户端,但是无法添加附件。
最后只能在Controller里面生成EML文件
注意: 在这里我曾使用过MomeyStream 直接作为附件, 但是提示文件损坏. 后面没有时间就没有继续研究了,. 目前是保存到服务器的一个文件夹里面.
下面是实现的代码:
Helper:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Mail;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc; namespace AgilityNorthAsiaPlatform.Code.Helpers
{
public class MailHelper
{ public static void ToEmlStream(System.Net.Mail.MailMessage msg, Stream str, string dummyEmail)
{
using (var client = new SmtpClient())
{
var id = Guid.NewGuid(); var tempFolder = Path.Combine(Path.GetTempPath(), Assembly.GetExecutingAssembly().GetName().Name); tempFolder = Path.Combine(tempFolder, "MailMessageToEMLTemp"); // create a temp folder to hold just this .eml file so that we can find it easily.
tempFolder = Path.Combine(tempFolder, id.ToString()); if (!Directory.Exists(tempFolder))
{
Directory.CreateDirectory(tempFolder);
} client.UseDefaultCredentials = true;
client.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
client.PickupDirectoryLocation = tempFolder;
client.Send(msg); // tempFolder should contain 1 eml file
var filePath = Directory.GetFiles(tempFolder).Single(); // create new file and remove all lines that start with 'X-Sender:' or 'From:'
string newFile = Path.Combine(tempFolder, "modified.eml");
using (var sr = new StreamReader(filePath))
{
using (var sw = new StreamWriter(newFile))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if (!line.StartsWith("X-Sender:") &&
!line.StartsWith("From:") &&
// dummy email which is used if receiver address is empty
!line.StartsWith("X-Receiver: " + dummyEmail) &&
// dummy email which is used if receiver address is empty
!line.StartsWith("To: " + dummyEmail))
{
sw.WriteLine(line);
}
}
}
} // stream out the contents
using (var fs = new FileStream(newFile, FileMode.Open))
{
fs.CopyTo(str);
}
}
} public static string ReadSignature()
{
string appDataDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Microsoft\\Signatures";
string signature = string.Empty;
DirectoryInfo diInfo = new DirectoryInfo(appDataDir);
if
(diInfo.Exists)
{
FileInfo[] fiSignature = diInfo.GetFiles("*.htm"); if (fiSignature.Length > 0)
{
StreamReader sr = new StreamReader(fiSignature[0].FullName, Encoding.Default);
signature = sr.ReadToEnd();
if (!string.IsNullOrEmpty(signature))
{
string fileName = fiSignature[0].Name.Replace(fiSignature[0].Extension, string.Empty);
signature = signature.Replace(fileName + "_files/", appDataDir + "/" + fileName + "_files/");
}
} }
return signature;
} }
}
Controller
public FileStreamResult ModalSendMail()
{
var report = new rpt_CFS_ShipmentReport_1();
report.ajs_Param.Value = (string)LocalViewData["SendMail_Json"];
report.as_Table.Value = "Con_Shp";
report.as_UsrID.Value = User.Identity.Name; var ReportStream = new MemoryStream();
report.ExportToPdf(ReportStream); string ls_filename = "Shipment Report" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf";
try
{
report.ExportToPdf(ReportStream);
FileStream fs = null;
fs = new FileStream(Path.Combine(Server.MapPath("~/FileUploads/"), ls_filename), FileMode.CreateNew);
fs.Write(ReportStream.GetBuffer(), 0, ReportStream.GetBuffer().Length);
fs.Flush();
fs.Close();
ReportStream.Flush();
ReportStream.Close();
}
catch (Exception ex)
{ } string dummyEmail = User.Identity.Name+"@xxx.com";
var mailMessage = new MailMessage();
mailMessage.To.Add(new MailAddress("xxx@xxx.com"));
mailMessage.From = new MailAddress(dummyEmail);
mailMessage.Subject = "Test subject";
mailMessage.IsBodyHtml = true;
mailMessage.Body = "Test body" + MailHelper.ReadSignature(); // mark as draft
mailMessage.Headers.Add("X-Unsent", "1"); // download image and save it as attachment
using (var httpClient = new HttpClient())
{
//download file from HTTP:
//var imageStream = await httpClient.GetStreamAsync(new Uri(Path.Combine(Server.MapPath("~/FileUploads/"), ls_filename)));
//mailMessage.Attachments.Add(new Attachment(HttpContext.Server.MapPath("~/App_Data/Test.docx")));
mailMessage.Attachments.Add(new System.Net.Mail.Attachment(Path.Combine(Server.MapPath("~/FileUploads/"), ls_filename), MediaTypeNames.Application.Pdf));
}
var stream = new MemoryStream();
MailHelper.ToEmlStream(mailMessage, stream, "jahe@agility.com");
stream.Position = 0;
return File(stream, "message/rfc822", "test_email.eml");
}
ASP.NET MVC 生成EML文件的更多相关文章
- [代码示例]用Fine Uploader+ASP.NET MVC实现ajax文件上传
原文 [代码示例]用Fine Uploader+ASP.NET MVC实现ajax文件上传 Fine Uploader(http://fineuploader.com/)是一个实现 ajax 上传文件 ...
- ASP.NET MVC 导出CSV文件
ASP.NET MVC 导出CSV文件.直接贴代码 /// <summary> /// ASP.NET MVC导出CSV文件Demo1 /// </summary> /// ...
- ASP.NET MVC下使用文件上传
这里我通过使用uploadify组件来实现异步无刷新多文件上传功能. 1.首先下载组件包uploadify,我这里使用的版本是3.1 2.下载后解压,将组件包拷贝到MVC项目中 3. 根目录下添加新 ...
- (一)【转】asp.net mvc生成验证码
网站添加验证码,主要为防止机器人程序批量注册,或对特定的注册用户用特定程序暴力破解方式,以进行不断的登录.灌水等危害网站的操作.验证码被广泛应用在注册.登录.留言等提交信息到服务器端处理的页面中. ...
- ASP.Net MVC 生成安全验证码
---------html <td>验证码:</td> <td> <img src="/Logi ...
- 用Fine Uploader+ASP.NET MVC实现ajax文件上传[代码示例]
Fine Uploader(http://fineuploader.com/)是一个实现 ajax 上传文件的 Javascript 组件. This project attempts to achi ...
- ASP.NET MVC上传文件----uploadify的使用
课程设计需要实现上传文件模块,本来ASP.NET是有内置的控件,但是ASP.NET MVC没有,所以就有两种方法:自定义和采用第三方插件.由于时间的关系,故采用第三方插件:uploadify. upl ...
- Asp.Net MVC 文件管理Demo(文件展示,上传,下载,压缩,文件重命名等)
之前 ,有想做一个文件管理页面. 参考了 许多资料,终于完成了一个基于Asp.net MVC 的文件管理Demo.界面如下. 一,实现功能及相关技术 文件管理Demo基于Asp.NET MVC , ...
- ASP.NET MVC上传文件
最近参考网络资料,学习了ASP.NET MVC如何上传文件.最基本的,没有用jQuery等技术. 1.定义Model public class TestModel { [Displ ...
随机推荐
- 【miscellaneous】星光级超低照度摄像机技术分析
低照度摄像机采用了超灵敏度图像传感器和独有的电子倍增和噪点控制技术能够极大地提高摄像机的灵敏度,并且具备24小时全彩色实时效果,绝无普通低照度摄像机出现的拖尾现象,以满足对夜间高品质监控的需求. ...
- 深入理解java:2.3.6. 并发编程concurrent包 之管理类---线程池
我们使用线程的时候就去创建一个线程,这样实现起来非常简便,但是就会有一个问题: 如果并发的线程数量很多,并且每个线程都是执行一个时间很短的任务就结束了,这样频繁创建线程就会大大降低系统的效率,因为频繁 ...
- 深入理解java:2.3.4. 并发编程concurrent包 之容器ConcurrentLinkedQueue(非阻塞的并发队列---循环CAS)
1. 引言 在并发编程中我们有时候需要使用线程安全的队列. 如果我们要实现一个线程安全的队列有两种实现方式:一种是使用阻塞算法,另一种是使用非阻塞算法. 使用阻塞算法的队列可以用一个锁(入队和出 ...
- linux挂载 mount
挂载(mounting)是指由操作系统使一个存储设备(诸如硬盘.CD-ROM或共享资源)上的计算机文件和目录可供用户通过计算机的文件系统访问的一个过程. Linux系统下目录和磁盘是分开的,磁盘上的文 ...
- 4、android studio打包的时候遇到的问题
那就去掉该签名 但是如果使用generated apk的话,则是不会去调用build.gradle文件的,需要使用gradle命令来打包 https://blog.csdn.net/cencibuqi ...
- HDU 3182 ——A Magic Lamp(思维)
Description Kiki likes traveling. One day she finds a magic lamp, unfortunately the genie in the lam ...
- jupyter notebook 使用多个python环境
conda install nb_conda_kernels 执行上面的命令,然后启动notebook就可以选择conda中的所有环境了
- 虚机Linux最小系统下安装图形界面,与yum配置
出于未知原因,想装一下. 因为有光盘,所以就从光盘安装就可以了. 首先是配置yum下的下载地址: 找到yum的地址,然后打开文件. 然后建立该文件的/media/cdrom路径.将光盘挂载到该路径下. ...
- Linux FTP的安装与权限配置
ftp安装部分,操作步骤如下: 1.切换到root用户 2.查看是否安装vsftp,我这个是已经安装的. [root@localhost vsftpd]# rpm -qa |grep vsftpd v ...
- 剑指offer-2:斐波那契数列
二.斐波那契数列 题目描述 大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0). n<=39 1.递归法 1). 分析 斐波那契数列的标准公式为 ...