最近在用 LumiSoft 进行邮件读取,然后操作相关附件
邮件使用的是qq邮箱,读取后进行移除,但是怎么都移除不了 后来咨询了官方客服,
原来是设置不对 需要 取消掉 X禁止收信软件删信 (仅对 POP3 协议有效。为什么会有收信软件删信?)
-----另外附上我写的相关代码
using LumiSoft.Net.Log;
using LumiSoft.Net.Mail;
using LumiSoft.Net.MIME;
using LumiSoft.Net.POP3.Client;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Net;
using System.Text;
using System.Linq;
namespace MCP.Sync.MailAttachCenter
{
public class MailAttachCenterBiz
{
// const string smtp = "imap.exmail.qq.com";
const string smtp = "pop.exmail.qq.com";
const int smtpport = 995;
const string user = "";
const string pwd = "";
const string dirfolder = @"D:\email\";
const string FileServerUrl = "";
const string module = "module_Sys_MailAttachCenter";
const string folderId = "folderId_Sys_MailAttachCenter";
public void SyncMail(ref string returnMessage)
{
using (POP3_Client pop3 = new POP3_Client())
{
//这里面存在无法删除邮件,所以导致只能通过去重的方式来处理重复读取的问题
var attachList =new List();
using (var db=new MCPERP_MailAttachEntities())
{
attachList = db.Sys_MailAttachCenter.Select(s => new MailAttach { MUID=s.MUID}).ToList();
}
pop3.Connect(smtp, smtpport, true);
pop3.Login(user, pwd);//两个参数,前者为Email的账号,后者为Email的密码
pop3.Logger = new Logger();
pop3.Logger.WriteLog += new EventHandler(WriteLog);
POP3_ClientMessageCollection messages = pop3.Messages;
for (int i = 0; i < messages.Count; i++)
{
var mEntity = new Sys_MailAttachCenter();
mEntity.SMTPServerName = smtp;
Dictionary dic_file = new Dictionary();
POP3_ClientMessage message = messages[i];//转化为POP3
if (attachList.Find(x=>x.MUID==message.UID)!=null)
{
continue;
}
pop3.Logger.AddText("\r\n正在检查第{0}封邮件..."+ i + 1);
if (message != null)
{
mEntity.MUID = message.UID;
byte[] messageBytes = message.MessageToByte();
if (messageBytes != null && messageBytes.Length > 0)
{
Mail_Message mime_message = Mail_Message.ParseFromByte(messageBytes);
Mail_Message mime_header = Mail_Message.ParseFromByte(message.HeaderToByte());
if (mime_header != null)
{
mEntity.Subject =!string.IsNullOrEmpty( mime_header.Subject)? mime_header.Subject.Trim():string.Empty;
mEntity.SendDT = mime_header.Date;
//区分抄送人
if (mime_header.Cc != null)
{
StringBuilder sb = new StringBuilder();
foreach (Mail_t_Mailbox recipient in mime_header.Cc.Mailboxes)
{
string displayname = recipient.DisplayName;
string address = recipient.Address;
sb.AppendFormat("{0};", address);
}
mEntity.CC = sb.ToString().Trim(';');
}
if (mime_header.From != null)
{
StringBuilder sb = new StringBuilder();
StringBuilder sb_sender = new StringBuilder();
foreach (Mail_t_Mailbox recipient in mime_header.From)
{
string displayname = recipient.DisplayName;
string address = recipient.Address;
sb.AppendFormat("{0};", address);
sb_sender.AppendFormat("{0};", displayname);
}
mEntity.Sender = sb_sender.ToString().Trim(';');
mEntity.FromMail = sb.ToString().Trim(';');
}
if (mime_header.To != null)
{
StringBuilder sb = new StringBuilder();
foreach (Mail_t_Mailbox recipient in mime_header.To.Mailboxes)
{
string displayname = recipient.DisplayName;
string address = recipient.Address;
sb.AppendFormat("{0};", address);
}
mEntity.ToMail = sb.ToString().Trim(';');
}
}
var body = mime_message.BodyText;
if (body != null)
{
mEntity.Body = body.Length > 1000 ? "超长被截断--"+body.Substring(0,990) : body;
}
//保存邮件的整体附件
DirectoryInfo dir = new DirectoryInfo(dirfolder);
if (!dir.Exists) dir.Create();
string emailPath = dirfolder + message.UID + ".eml";
File.WriteAllBytes(emailPath, messageBytes);
dic_file.Add(Guid.NewGuid().ToString(), emailPath);
//附件处理
MIME_Entity[] attachments = mime_message.GetAttachments(true, true);
mEntity.AttachmentsCount = 1;
if (attachments != null && attachments.Length > 0)
{
mEntity.AttachmentsCount = mEntity.AttachmentsCount+attachments.Length;
foreach (MIME_Entity entity in attachments)
{
if (entity.ContentDisposition != null)
{
string fileName = entity.ContentDisposition.Param_FileName;
if (!string.IsNullOrEmpty(fileName))
{
var dirFileName = GetValidName(message.UID + fileName);
string path = Path.Combine(dir.FullName, dirFileName);
MIME_b_SinglepartBase byteObj = (MIME_b_SinglepartBase)entity.Body;
Stream decodedDataStream = byteObj.GetDataStream();
using (FileStream fs = new FileStream(path, FileMode.Create))
{
LumiSoft.Net.Net_Utils.StreamCopy(decodedDataStream, fs, 4000);
}
dic_file.Add(Guid.NewGuid().ToString(), path);
//这里实现上传附件
//上传成功以后删除本地缓存的附件
pop3.Logger.AddText($"{fileName}已经被下载。");
}
}
}
}
}
var result = SaveFileToServer(dic_file, mEntity);//保存文件方法
if (result)
{
message.MarkForDeletion();//移除这个邮件
}
}
}
}
}
public static string GetValidName(string fileName)
{
foreach (char c in System.IO.Path.GetInvalidFileNameChars())
{
fileName = fileName.Replace(c, ' ');
}
return fileName;
}
private void WriteLog(object sender, WriteLogEventArgs e)
{
if (e!=null && e.LogEntry!=null)
{
}
}
///
/// 保存附件到文件服务器并添加到
///
///
private bool SaveFileToServer(Dictionary dir, Sys_MailAttachCenter mEntity)
{
try
{
if (mEntity!=null && dir.Count>0)
{
var fList = new List();
foreach (var item in dir)
{
string address = FileServerUrl + string.Format("Home/UploadFile?module={0}&folderId={1}&uploadDate={2}", module, folderId, DateTime.Now.ToString("yyyyMMdd"));
var buffer = new WebClient().UploadFile(address, "post", item.Value);
string result = Encoding.UTF8.GetString(buffer);
var fileServerPath = FileServerUrl + result.Replace("~/", "");
//判断文件是不是存在 清空临时存储的文件
if (System.IO.File.Exists(item.Value))
{
System.IO.File.Delete(item.Value);
}
Sys_FileInfo file = new Sys_FileInfo();
file.CreateDT = DateTime.Now;
file.CreaterName = module;
file.Description ="邮件附件处理中心创建";
file.FileType = Path.GetExtension(item.Value);
file.folderId = folderId;
file.module = module;
file.FileJobno = mEntity.MUID.ToString();
file.FileId = Guid.NewGuid().ToString("N");
file.EnabledMark = 1;
file.DeleteMark = 0;
file.FilePath = fileServerPath;
file.FileName = Path.GetFileName(item.Value);
file.FileExtensions = Path.GetExtension(item.Value);
fList.Add(file);
}
using (var db = new MCPERP_MailAttachEntities())
{
db.Sys_FileInfo.AddRange(fList);
mEntity.CreateDT = DateTime.Now;
mEntity.IsRead = false;
mEntity.IsReply = false;
db.Sys_MailAttachCenter.Add(mEntity);
db.SaveChanges();
}
return true;
}
return false;
}
catch (Exception ex)
{
throw ex;
}
}...
}
public class MailAttach
{
public string MUID { get; set; }
}
}