我们会定期发送电子邮件(请求将由用户驱动),其中包含Excel附件。目标是自动从电子邮件中提取附件,并将其传递给处理文件中数据的方法。
我希望远离第三方工具或图书馆,我希望尽可能保持简单,最少的检查和功能,只需下载邮件,保存附件,如果电子邮件地址与已知来源匹配(阻止垃圾邮件)。
从研究来看,有3种可能的解决方案。哪条路最合理呢?还有其他选择吗?有人能指出我相关的(和最近的)教程吗?
答案 0 :(得分:0)
以下是我如何使用我们的系统进行操作的示例。如果您希望我解释任何内容,请告诉我,因为我必须快速发布此内容。
namespace Namespace.Email
{
public class EmailLinker
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
public EmailLinker()
{
service.Credentials = new NetworkCredential("username", "password", "domain");
service.AutodiscoverUrl("email@email.com");
}
public void linkEmails()
{
FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, new ItemView(128));
if (findResults.TotalCount > 0)
{
ServiceResponseCollection<GetItemResponse> items = service.BindToItems(findResults.Select(item => item.Id), new PropertySet(BasePropertySet.FirstClassProperties, EmailMessageSchema.From, EmailMessageSchema.ToRecipients));
foreach (GetItemResponse i in items)
{
MailItem m = new MailItem();
Item it = i.Item;
m.From = ((Microsoft.Exchange.WebServices.Data.EmailAddress)it[EmailMessageSchema.From]).Address;
m.Recipients = ((Microsoft.Exchange.WebServices.Data.EmailAddressCollection)it[EmailMessageSchema.ToRecipients]).Select(r => r.Address).ToArray();
m.Subject = it.Subject;
m.Body = it.Body.Text;
m.Recieved = it.DateTimeReceived;
m.attachments = it.Attachments;
foreach (Attachment a in m.attachments)
this.uploadAttachments(a);
i.Item.Delete(DeleteMode.HardDelete);
}
}
}
private void uploadAttachments(Attachment a)
{
ContentFile cf = new ContentFile();
cf.Name = a.Name;
cf.Size = a.Size;
cf.ContentType = MimeTypeMap.GetMimeType(Path.GetExtension(a.Name).Replace(".",""));
FileAttachment fa = (FileAttachment)a;
fa.Load();
cf.Data = fa.Content;
cf.DateAdded = DateTime.Now;
cf.save();
}
public class MailItem
{
public int id;
public string From;
public string[] Recipients;
public string Subject;
public string Body;
public DateTime Recieved;
public string RecievedString
{
get
{
return Recieved.ToShortDateString() + " " + Recieved.ToShortTimeString();
}
}
public AttachmentCollection attachments;
}
}
}
答案 1 :(得分:0)
public class KCSExchangeLink : IKCSExchangeLink
{
private bool CertificateValidationCallBack(
object sender,
System.Security.Cryptography.X509Certificates.X509Certificate certificate,
System.Security.Cryptography.X509Certificates.X509Chain chain,
System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
// If the certificate is a valid, signed certificate, return true.
if (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None)
{
return true;
}
// If there are errors in the certificate chain, look at each error to determine the cause.
if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) != 0)
{
if (chain != null && chain.ChainStatus != null)
{
foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus status in chain.ChainStatus)
{
if ((certificate.Subject == certificate.Issuer) &&
(status.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.UntrustedRoot))
{
// Self-signed certificates with an untrusted root are valid.
continue;
}
else
{
if (status.Status != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError)
{
// If there are any other errors in the certificate chain, the certificate is invalid,
// so the method returns false.
return false;
}
}
}
}
// When processing reaches this line, the only errors in the certificate chain are
// untrusted root errors for self-signed certificates. These certificates are valid
// for default Exchange server installations, so return true.
return true;
}
else
{
// In all other cases, return false.
return false;
}
}
private bool RedirectionUrlValidationCallback(string redirectionUrl)
{
// The default for the validation callback is to reject the URL.
bool result = false;
Uri redirectionUri = new Uri(redirectionUrl);
// Validate the contents of the redirection URL. In this simple validation
// callback, the redirection URL is considered valid if it is using HTTPS
// to encrypt the authentication credentials.
if (redirectionUri.Scheme == "https")
{
result = true;
}
return result;
}
public void SaveAttachment(string email, string password, string downloadfolder, string fromaddress)
{
ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
service.Credentials = new WebCredentials(email, password);
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
service.AutodiscoverUrl(email, RedirectionUrlValidationCallback);
// Bind the Inbox folder to the service object.
Folder inbox = Folder.Bind(service, WellKnownFolderName.Inbox);
// The search filter to get unread email.
SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
ItemView view = new ItemView(1);
// Fire the query for the unread items.
// This method call results in a FindItem call to EWS.
FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, sf, view);
foreach (EmailMessage item in findResults)
{
item.Load();
/* download attachment if any */
if (item.HasAttachments && item.Attachments[0] is FileAttachment && item.From.Address == fromaddress)
{
FileAttachment fileAttachment = item.Attachments[0] as FileAttachment;
/* download attachment to folder */
fileAttachment.Load(downloadfolder + fileAttachment.Name);
}
/* mark email as read */
item.IsRead = true;
item.Update(ConflictResolutionMode.AlwaysOverwrite);
}
}
}