ic = new ImapClient("imap.yandex.com", Email, email.Password, AuthMethods.Login, 993, true);
var mailMessage = ic.SearchMessages(SearchCondition.From("somemail#gmail.com"), false, true).ToList();
if (mailMessage.Count > 0)
{
foreach (Lazy<AE.Net.Mail.MailMessage> Lmail in mailMessage)
{
AE.Net.Mail.MailMessage mail = Lmail.Value;
//SendSmtpMail(mail.Subject, ReplyData, Email, Password, mail.From,mail.MessageID);
if (mail != null)
{
if (mail.To.FirstOrDefault(x => x.Equals(email.EmailName)) != null)
{
if (mail.Body.IndexOf("Attachment Name:", StringComparison.OrdinalIgnoreCase) > -1)
{
Code= Between(mail.Body, "to:", "\r");
}
else
{
_msg.Add("CODE NOT FOUND..." + Environment.NewLine);
}
}
}
}
}
I'm using AE Mail plugin from nuget. Problem is, the following line:
AE.Net.Mail.MailMessage mail = Lmail.Value;
took almost 1 second for lazy enumeration. This is so bothering when parsing lots of mails. Any suggestions?
Related
I have code that read email attachments, embedded and not embedded, but if have both in the same email, only read embedded attachment.
Any help will be appreciated..
My code.
{
string strFiltro = String.Format("SINCE {0}-{1}-{2} BEFORE {3}-{4}-{5} {6} ",
strDiaInicial,
strMesInicial,
strAnioInicial,
strDiaFinal,
strMesFinal,
strAnioFinal,
(this.MensajesNoLeidos == true ? "UNSEEN" : "ALL"));
IEnumerable<Message> mensajesFiltrados = folder.Search(strFiltro/*MessageFetchMode.Full,10*/);
mensajesFiltrados = mensajesFiltrados.Where(x => x.Attachments.Count() > 0 || x.EmbeddedResources.Count() > 0);
foreach (Message message in mensajesFiltrados)
{
if (message.Attachments.Count() > 0)
{
ArchivosAdjuntosFiltrados = message.Attachments.Where(x => x.ContentType.Name.ToLower().Contains(".pdf")) x.ContentType.Name.ToLower().Contains(".xml"));
resultado[0] = resultado[0] + ArchivosAdjuntosFiltrados.Count();
}
else
{
if (message.EmbeddedResources.Count() > 0)
{
//never get Embedded pdf or xml files ArchivosAdjuntosFiltrados = message.EmbeddedResources.Where(x => x.ContentType.Name.Contains(".pdf") || x.ContentType.Name.Contains(".xml"));
}
}
}
foreach (Attachment atachemtn in ArchivosAdjuntosFiltrados)
{
strNombreArchivo = atachemtn.FileName;
String attachData = atachemtn.GetTextData().Replace('-', '+'); attachData = attachData.Replace('_', '/');
if (intPosicion > 0)
{
attachData = attachData.Substring(0, attachData.Length - 31);
}
if (strNombreArchivo != String.Empty)
{
if (File.Exists(Path.Combine(strRutaDescargas, atachemtn.FileName)) == true)
{
if (pBlnSobreescribirArchivos == true)
{
byte[] data = Convert.FromBase64String(attachData);
File.WriteAllBytes(Path.Combine(this.strRutaDescargas, strNombreArchivo), data);
}
}
}
}
}
}
I have an ActionResult method and at the end I want it to return the success page. It hits the return View("ExportFile") but nothing ever happens.
Here is my action method:
[HttpPost]
//[ValidateAntiForgeryToken]
public ActionResult ExportFile(string[] years, string[] months, string[] radio, string[] emails, string acctNum)
{
// Is Account Number empty or Radio not selected
if (String.IsNullOrEmpty(acctNum.Trim()) && radio == null)
{
return Json(new { success = false, message = "* Please Enter Account Number\n\n * Please choose whether to download or email statements" });
}
if (acctNum == "")
{
return Json(new { success = false, message = "* Please Enter Account Number" });
}
else if (radio == null)
{
return Json(new { success = false, message = "* Please Choose whether To Download or Email" });
}
try
{
// If only account number is entered
if (years == null)
{
if (months == null)
{
using (var db = new FMBDBPRDEntities1())
{
allPaths = db.ClientStatement_Inventory
.Where(x => x.accountNum == acctNum)
.Select(c => c.statementPath).ToList();
}
if (allPaths.Count == 0)
{
return Json(new { success = false, message = $"There were no documents for Account#: {acctNum}" });
}
}
}
// If "Emailing Statements" is chosen
else if (radio[0] == "Email Statements")
{
// Make array of emails into List for sending in email
if (emails.ToString() != "")
{
var allEmails = emails[0].Split(',');
foreach (var email in allEmails)
{
if (emailValid.IsMatch(email))
{
everyEmail.Add(email);
}
else
{
return Json(new { success = false, message = $"* Not valid email address: {email}.\n\n * Please double check and try again." });
}
}
MemoryStream output = new MemoryStream();
List<string> distinctFiles = allPaths
.GroupBy(x => x.Split(new char[] { '\\' }).Last())
.Select(x => x.First())
.ToList();
using (ZipFile zip = new ZipFile())
{
zip.AddFiles(distinctFiles, #"\");
zip.Save(output);
output.Position = 0;
var attachmentResult = output.Length;
if (attachmentResult > 24500000)
{
return Json(new { success = false, message = "* Email attachment is too large.\n\n * Please select Download to download your files. " });
}
else
{
return View("ExportFile");
//DBQueries.SendEmail(everyEmail, output, fromAddress, "Client Statement Reports", "", true);
}
At the very end "return View("ExportFile") will not return my view called ExportFile. The action name and the return view needs to be the same names correct?
This problem is happening for one of our customers and I have been unable to replicate on my side using the same version of Outlook. My customer and I are using Office 365 with Outlook 2016 installed. When he sends an email in our program via Outlook Redemption (a third party program used for Outlook integration), the mail gets stuck in his outbox.
If he double clicks the message (so it pops up in Outlook) he can hit the send button and it will sucessfuly send. If they use an old version of Outlook (2010) this is not a problem. I upgraded them to the the newest version of Outlook Redmeption at the time (released May 07, 2016), though it looks like they just came out with a new version a few days ago. I'll try that soon, but the changelog doesn't mention mail getting stuck in the Outbox.
I also noticed that the emails in his outbox have what appears to be the 'draft' symbol on them, while in my outbox they have a 'sending' symbol on them. This seems important, but I'm not sure what I can do about that.
Also, hitting Send/Receive All Folders does not help.
My code is below. Thank you for any assistance.
public static bool SendMessage(Recipients recipients, string[] addressListReplyTo, string subject, string body, string[] attachments, bool requestReadReceipt, Log log, bool isHtmlBody = false)
{
RDOSession session = null;
RDOMail mail;
RDOFolder folder;
bool result = true;
session = GetSessionAndLogon(log);
if (session == null)
return false;
folder = session.GetDefaultFolder(rdoDefaultFolders.olFolderOutbox);
mail = folder.Items.Add();
if (isHtmlBody)
mail.HTMLBody = body;
else
mail.Body = body;
mail.Subject = subject;
mail.ReadReceiptRequested = requestReadReceipt;
foreach (string attachment in attachments)
{
if (attachment != "")
mail.Attachments.Add(attachment);
}
foreach (string address in addressListReplyTo)
{
if (address != "")
mail.ReplyRecipients.Add(address);
}
foreach (string address in recipients.To)
{
if (address != "")
mail.Recipients.Add(address).Type = 1;
}
foreach (string address in recipients.Cc)
{
if (address != "")
mail.Recipients.Add(address).Type = 2;
}
foreach (string address in recipients.Bcc)
{
if (address != "")
mail.Recipients.Add(address).Type = 3;
}
foreach (RDORecipient recipient in mail.Recipients)
{
if (!OutlookMailEngine64.existsName(recipient.Name, session, log == null ? null : log))
result = false;
}
if (result)
{
try
{
mail.Send();
result = true;
}
catch (System.Runtime.InteropServices.COMException ex)
{
string message = "Error while sending email: " + ex.Message;
if (log != null)
log.Message(message);
if (OutlookMailEngine64.DiagnosticMode)
MessageBox.Show(message);
throw new EmailLibraryException(EmailLibraryException.ErrorType.InvalidRecipient, "One or more recipients are invalid (use OutlookMailEngine64.ValidateAddresses first)", ex);
}
}
if (session.LoggedOn)
session.Logoff();
return result;
}
Keep in mind that message submission is asynchronous, and it will nto be automatically triggered unless you are using the online Exchange store (where store and transport provider are tightly coupled).
You can force send/receive by calling Namespace.SendAndReceive in the Outlook Object Model.
Dmitry worked with me via email. The solution for me was to swap out RDO for the SafeMailItem object. Here is the updated version of my method so you can see the changes:
private static bool SendSafeMessage(Recipients recipients, string[] addressListReplyTo, string subject, string body, string[] attachments, bool requestReadReceipt, Log log, bool isHtmlBody = false)
{
//This method was added because sometimes messages were getting stuck in the Outlook Outbox and this seems to solve that
bool result = true;
Microsoft.Office.Interop.Outlook.Application application = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.NameSpace namespaceMAPI = application.GetNamespace("MAPI");
namespaceMAPI.Logon();
RDOSession session = null;
session = GetSessionAndLogon(log); //TODO: I'm creating a 2nd session here which is wasteful
SafeMailItem safeMail = Redemption.RedemptionLoader.new_SafeMailItem();
Microsoft.Office.Interop.Outlook.MailItem outlookMailItem = (Microsoft.Office.Interop.Outlook.MailItem)application.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
safeMail.Item = outlookMailItem;
if (isHtmlBody)
outlookMailItem.HTMLBody = body;
else
safeMail.Body = body;
outlookMailItem.Subject = subject;
outlookMailItem.ReadReceiptRequested = requestReadReceipt;
foreach (string attachment in attachments)
{
if (attachment != "")
safeMail.Attachments.Add(attachment);
}
foreach (string address in addressListReplyTo)
{
if (address != "")
safeMail.ReplyRecipients.Add(address);
}
foreach (string address in recipients.To)
{
if (address != "")
safeMail.Recipients.Add(address).Type = 1;
}
foreach (string address in recipients.Cc)
{
if (address != "")
safeMail.Recipients.Add(address).Type = 2;
}
foreach (string address in recipients.Bcc)
{
if (address != "")
safeMail.Recipients.Add(address).Type = 3;
}
foreach (Microsoft.Office.Interop.Outlook.Recipient recipient in outlookMailItem.Recipients)
{
if (!OutlookMailEngine64.existsName(recipient.Name, session, log == null ? null : log))
result = false;
}
if (result)
{
try
{
safeMail.Send();
result = true;
}
catch (System.Runtime.InteropServices.COMException ex)
{
string message = "Error while sending email: " + ex.Message;
if (log != null)
log.Message(message);
if (OutlookMailEngine64.DiagnosticMode)
MessageBox.Show(message);
throw new EmailLibraryException(EmailLibraryException.ErrorType.InvalidRecipient, "One or more recipients are invalid (use OutlookMailEngine64.ValidateAddresses first)", ex);
}
}
if (session.LoggedOn)
session.Logoff();
namespaceMAPI.Logoff();
return result;
}
We have the below code to read the attachments using EWS.
FindItemsResults<Item> foundItems = service.FindItems(FolderId, new ItemView(1000));
var orderItems = from list in foundItems
orderby list.DateTimeReceived
select list;
foreach (EmailMessage item in orderItems)
{
item.Load();//SARANYA
EmailMessage foundEmail = (EmailMessage)item;
EmailMessage message = EmailMessage.Bind(service, new ItemId(item.Id.ToString()), new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.Attachments, ItemSchema.Body));
if (message.Attachments.Count > 0)
{
FileAttachment[] attachments = null;
attachments = new FileAttachment[message.Attachments.Count];
foreach (Attachment attachment in message.Attachments)
{
try
{
if (attachment is FileAttachment)
{
FileAttachment fileAttachment = attachment as FileAttachment;
// System.Threading.Thread.Sleep(2000);
fileAttachment.Load();
byte[] FolloupMailFileAttachmentContentBytes = fileAttachment.Content;
bool isScreenshot = false;
string ScreenfileName = "";
for (int i = 0; i < imgSrcs.Count; i++)
{
if (imgSrcs[i].ToString() == fileAttachment.Name.ToString())
{
isScreenshot = true;
if (!imgSrcs[i].ToString().Contains(".png"))
ScreenfileName = "cid:" + imgSrcs[i].ToString() + ".png";
else
ScreenfileName = "cid:" + imgSrcs[i].ToString();
break;
}
}
if (FolloupMailFileAttachmentContentBytes != null)
{
if (isScreenshot && RemoveSuccess == 1)
{
InsertMailItemAttachment(ScreenfileName, FolloupMailFileAttachmentContentBytes, caseid);
}
else
InsertMailItemAttachment(fileAttachment.Name.ToString(), FolloupMailFileAttachmentContentBytes, caseid);
}
}
else if (attachment is ItemAttachment)
{
item.Move(unreadmailFolder.Id);
}
}
catch (Exception exe)
{
if (!ReadMoved)
{
item.Move(readmailFolder.Id);
ReadMoved = true;
}
logfile.HandleError(exe, "Attachment Exception \n\nEmailbox - " + EMailBox + "\n\nEmail Subject - " + strSubject + " \n - Could not load the attachment (" + attachment.Name.ToString() + ")");
}
}
}
}
Above code is working when I provide thread.sleep() before fileattachment.load(). when thread.sleep is removed, I get the below exception.
Error Source : Microsoft.Exchange.WebServices
Target Site : Void InternalThrowIfNecessary()
System Message : The specified object was not found in the store.
Stack Trace : at Microsoft.Exchange.WebServices.Data.ServiceResponse.InternalThrowIfNecessary()
at Microsoft.Exchange.WebServices.Data.ServiceResponse.ThrowIfNecessary()
at Microsoft.Exchange.WebServices.Data.MultiResponseServiceRequest`1.Execute()
at Microsoft.Exchange.WebServices.Data.ExchangeService.InternalGetAttachments(IEnumerable`1 attachments, Nullable`1 bodyType, IEnumerable`1 additionalProperties, ServiceErrorHandling errorHandling)
at Microsoft.Exchange.WebServices.Data.ExchangeService.GetAttachment(Attachment attachment, Nullable`1 bodyType, IEnumerable`1 additionalProperties)
at Microsoft.Exchange.WebServices.Data.Attachment.InternalLoad(Nullable`1 bodyType, IEnumerable`1 additionalProperties)
at Microsoft.Exchange.WebServices.Data.Attachment.Load()
at EMT_Office365_MailFetch_Scheduler.Program.FindEmail(Object threadState) in
Experts, Please provide your valuable inputs
Your logic doesn't look correct eg
item.Move(unreadmailFolder.Id);
Should not be inside the Foreach loop if you want to move the message at the end just use a Flag and process it once you have finished processing the attachments(you logic doesn't work if you have two ItemAttachment this would execute twice). The reason sleep is working is mostly likely an Aysnc operation is completing once you have executed the move. Thats why this should be outside of the foreach attachment loop
I have a problem with mailing to a exchange server.
The mails got delivered, but the SmtpClient always waits for 8 seconds and then receives a timeout exception.
I think it has something to do with the exchange mail queue, but i don't find a fix for it.
Best regards,
Michael
public void SendMessage(MailMessage message, string guid)
{
if(!ValidSettings())
{
return;
}
if(!string.IsNullOrEmpty(_bccEmail))
{
message.Bcc.Add(_bccEmail);
}
message.From = new MailAddress(_emailFrom, _weergaveNaam);
bool error = true;
int tried = 0;
while(error && tried < _maxRetry)
{
if(_smtpClient == null)
{
_smtpClient = new SmtpClient(_serverUrl, _serverPort) {Credentials = new NetworkCredential(_serverUser, _serverPassword), EnableSsl = _useSsl};
}
using(UnitOfWork uow = new UnitOfWork())
{
tried++;
EmailLog log = new EmailLog(uow) {Guid = guid, From = message.From.Address};
StringBuilder sb = new StringBuilder();
foreach(MailAddress mailAddress in message.To)
{
if(sb.Length > 0)
{
sb.Append(",");
}
sb.Append(mailAddress.Address);
}
log.To = sb.ToString();
sb.Clear();
foreach (MailAddress mailAddress in message.Bcc)
{
if (sb.Length > 0)
{
sb.Append(",");
}
sb.Append(mailAddress.Address);
}
log.Bcc = sb.ToString();
sb.Clear();
foreach (MailAddress mailAddress in message.CC)
{
if (sb.Length > 0)
{
sb.Append(",");
}
sb.Append(mailAddress.Address);
}
log.Cc = sb.ToString();
sb.Clear();
log.Subject = message.Subject;
try
{
_smtpClient.Timeout = 8000;
_smtpClient.Send(message);
log.EmailStatus = EmailStatusEnum.Succes;
error = false;
}
catch(SmtpException ex)
{
log.EmailStatus = EmailStatusEnum.Error;
log.ServerMessage = ex.Message;
log.ServerCode = ex.StatusCode.ToString();
error = true;
}
catch(Exception ex)
{
log.EmailStatus = EmailStatusEnum.Error;
log.ServerMessage = ex.Message;
error = true;
}
finally
{
log.Save();
uow.CommitChanges();
}
}
}
message.Dispose();
}
Echange log :
http://pastebin.com/UUiNyVx8