I am developing a Console application which will monitor Exchange server and download attachments(XML Files) from new emails. I have used EaGetmail for this.
Attachments are downloading to target folder but it is empty. Looking for a solution.
This is my sample code, Any suggestions Pls.
private static void CheckInboxforEmail()
{
// Use domain\user as the user name
MailServer oServer = new MailServer("MailID", "domain","Pwd",ServerProtocol.ExchangeEWS);
MailClient oClient = new MailClient("TryIt");
oServer.SSLConnection = true;
try
{
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
for (int i = 0; i < infos.Length; i++)
{
MailInfo info = infos[i];
// Receive email from Exchange server
Mail oMail = oClient.GetMail(info);
//SaveAttachments
foreach (EAGetMail.Attachment Att in oMail.Attachments)
{
string AttName = String.Format("{0}\\{1}", WIPFolder,Att.Name);
oMail.SaveAs(AttName, true);
}
// Delete email from EWS server.
oClient.Delete(info);
}
// Quit from Exchange server.
oClient.Quit();
}
catch (Exception ep)
{
}
}
Try this it worked for me!!!!
//Get Attachments
Attachment[] atts = oMail.Attachments;
int count = atts.Length;
//Store Attachments
for (int ai = 0; ai < count; ai++)
{
Attachment att = atts[ai];
string attname = String.Format("{0}\\{1}", mailbox, att.Name);
att.SaveAs(attname, true);
}
Related
I'm trying to work with email data in my application. Everything works fine, I just need that when a new email arrives, it should also be read. This way only the emails are printed before the application starts. Is this possible in the EAGetEmails library using POP3 Server or do I have to program my own Sever or after some short time turn on and off the Application to update itself(This seems to me a rather clumsy solution)?
using EAGetMail;
using System;
using System.Globalization;
using System.IO;
namespace PopServer
{
class Program
{
static string _generateFileName(int sequence)
{
DateTime currentDateTime = DateTime.Now;
return string.Format("{0}-{1:000}-{2:000}.eml",
currentDateTime.ToString("yyyyMMddHHmmss", new CultureInfo("en-US")),
currentDateTime.Millisecond,
sequence);
}
static void Main(string[] args)
{
try
{
string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory());
if (!Directory.Exists(localInbox))
{
Directory.CreateDirectory(localInbox);
}
MailServer oServer = new MailServer("popserver.com",
"username#mail.com",
"password",
ServerProtocol.Pop3);
oServer.SSLConnection = true;
oServer.Port = 995;
MailClient oClient = new MailClient("TryIt");
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
Console.WriteLine("Total {0} email(s)\r\n", infos.Length);
//Here I tried to take advantage of the fact that if the application is connected via SSLConnection, it could update, but it only prints the emails before starting the application
while (oServer.SSLConnection)
{
for (int i = 0; i < infos.Length; i++)
{
MailInfo info = infos[i];
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
info.Index, info.Size, info.UIDL);
Mail oMail = oClient.GetMail(info);
Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);
Console.WriteLine("Body: {0}\r\n", oMail.TextBody);
string fileName = _generateFileName(i + 1);
string fullPath = string.Format("{0}\\{1}", localInbox, fileName);
oMail.SaveAs(fullPath, true);
//Delete email-isRead
//oClient.Delete(info);
}
}
oClient.Quit();
Console.WriteLine("Completed!");
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
EAGetMail is not really popular,you can take a look on this library : https://www.nuget.org/packages/OpenPop.NET/
public static List<Message> FetchAllMessages(string hostname, int port, bool useSsl, string username, string password)
{
// The client disconnects from the server when being disposed
using(Pop3Client client = new Pop3Client())
{
// Connect to the server
client.Connect(hostname, port, useSsl);
// Authenticate ourselves towards the server
client.Authenticate(username, password);
// Get the number of messages in the inbox
int messageCount = client.GetMessageCount();
// We want to download all messages
List<Message> allMessages = new List<Message>(messageCount);
// Messages are numbered in the interval: [1, messageCount]
// Ergo: message numbers are 1-based.
// Most servers give the latest message the highest number
for (int i = messageCount; i > 0; i--)
{
allMessages.Add(client.GetMessage(i));
}
// Now return the fetched messages
return allMessages;
}
}
Then you just have to code a little loop to check email every few secondes.
I'm trying to retrieve data from email and then work with it. Everything is fine, I can get the data, but I need to get the most recent ones. When I run this code and send an email in the process, it doesn't come up until I turn it on. I have tried turning the SSL connection or client to the server on and off and back on again (like some kind of update, but with the same result).
Thanks for any reaction or ideas. :)
using EAGetMail;
using System;
using System.Globalization;
using System.IO;
namespace PopServer
{
class Program
{
static string _generateFileName(int sequence)
{
DateTime currentDateTime = DateTime.Now;
return string.Format("{0}-{1:000}-{2:000}.eml",
currentDateTime.ToString("yyyyMMddHHmmss", new CultureInfo("en-US")),
currentDateTime.Millisecond,
sequence);
}
static void Main(string[] args)
{
try
{
string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory());
if (!Directory.Exists(localInbox))
{
Directory.CreateDirectory(localInbox);
}
MailServer oServer = new MailServer("popserver.com",
"username#mail.com",
"password",
ServerProtocol.Pop3);
oServer.SSLConnection = true;
oServer.Port = 995;
MailClient oClient = new MailClient("TryIt");
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
Console.WriteLine("Total {0} email(s)\r\n", infos.Length);
//Here I tried to take advantage of the fact that if the application is connected via SSLConnection, it could update, but it only prints the emails before starting the application
while (oServer.SSLConnection)
{
for (int i = 0; i < infos.Length; i++)
{
MailInfo info = infos[i];
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
info.Index, info.Size, info.UIDL);
Mail oMail = oClient.GetMail(info);
Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);
Console.WriteLine("Body: {0}\r\n", oMail.TextBody);
string fileName = _generateFileName(i + 1);
string fullPath = string.Format("{0}\\{1}", localInbox, fileName);
oMail.SaveAs(fullPath, true);
//Delete email-isRead
//oClient.Delete(info);
}
}
oClient.Quit();
Console.WriteLine("Completed!");
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
try
{
bool help = true;
do{
string localInbox = string.Format("{0}\\inbox",
Directory.GetCurrentDirectory());
if (!Directory.Exists(localInbox))
{
Directory.CreateDirectory(localInbox);
}
MailServer oServer = new MailServer("popserver.com",
"username#mail.com",
"password",
ServerProtocol.Pop3);
oServer.SSLConnection = true;
oServer.Port = 995;
MailClient oClient = new MailClient("TryIt");
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
Console.WriteLine("Total {0} email(s)\r\n", infos.Length);
//Here I tried to take advantage of the fact that if the application is connected via SSLConnection, it could update, but it only prints the emails before starting the application
while (oServer.SSLConnection)
{
for (int i = 0; i < infos.Length; i++)
{
MailInfo info = infos[i];
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
info.Index, info.Size, info.UIDL);
Mail oMail = oClient.GetMail(info);
Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);
Console.WriteLine("Body: {0}\r\n", oMail.TextBody);
string fileName = _generateFileName(i + 1);
string fullPath = string.Format("{0}\\{1}", localInbox, fileName);
oMail.SaveAs(fullPath, true);
//Delete email-isRead
//oClient.Delete(info);
}
}
Console.WriteLine("Again?");
Console.WriteLine("1-y");
Console.WriteLine("2-n");
int a = Convert.ToInt32(Console.ReadLine());
if (a == 2)
{
help = false;
}
//Just easily restarted hole code
while(help != false)
oClient.Quit();
Console.WriteLine("Completed!");
I want to automatically open or click a http link from the Outlook mail body.
I am using MailServer.
Here my code:
// Some function...
for (int i = 0; i < infos.Length; i++)
{
MailInfo info = infos[i];
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}; Flags: {3}",
info.Index, info.Size, info.UIDL, info.Flags);
// Receive email from POP3 server
Mail oMail = oClient.GetMail(info);
Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("To: {0}", oMail.To.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);
if (oMail.Attachments.Length > 0)
{
for (int j = 0; j <= oMail.Attachments.Length - 1; j++)
{
System.DateTime d = System.DateTime.Now;
System.Globalization.CultureInfo cur = new System.Globalization.CultureInfo("en-US");
string sdate = d.ToString("MMddyyyyHHmmss", cur);
string fileName = String.Format("{0}\\{1}{2}{3}.eml", mailbox, sdate, d.Millisecond.ToString("d3"), i);
// Save email to local disk
oMail.SaveAs(fileName, true);
// Save attachments in specific folders.
oMail.Attachments[j].SaveAs(#"D:\"{Folder Name}"\" + oMail.Attachments[j].Name, true); // find the said path
// Mark email as deleted from POP3 server.
oClient.Delete(info);
}
}
// Generate an email file name based on date time.
}
// Quit and purge emails marked as deleted from POP3 server.
oClient.Quit();
}
Please give me any idea.
Microsoft.Office.Interop.Outlook.Application Application = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MAPIFolder inBox = Application.ActiveExplorer().Session.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
Microsoft.Office.Interop.Outlook.Items inBoxItems = inBox.Items;
Microsoft.Office.Interop.Outlook.MailItem newEmail = null;
foreach (object collectionItem in inBoxItems)
{
newEmail = collectionItem as Microsoft.Office.Interop.Outlook.MailItem;
if (newEmail != null)
{
if (newEmail.Attachments.Count > 0)
{
for (int i = 1; i <= newEmail
.Attachments.Count; i++)
{
newEmail.Attachments[i].SaveAsFile
(#"C:\TestFileSave\" +
newEmail.Attachments[i].FileName);
}
}
}
}
I have copy mail from outlook and paste into flex-grid in window application but getting zero attachment count but in mail there are attachments like excel , doc , etc. files.
int extractFileParentId = pkUniqueId;
List<ZipExtracFile> extractFileList = lts;
MsgReader.Outlook.Storage.Message message = new MsgReader.Outlook.Storage.Message(fileNames);
foreach (var attachment in message.Attachments)
{
string fileName = string.Empty;
pkUniqueId = pkUniqueId + 1;
if (attachment.GetType() == typeof(MsgReader.Outlook.Storage.Attachment))
{
var attach = (MsgReader.Outlook.Storage.Attachment)attachment;
fileName = Path.Combine(tempPath, (attach).FileName);
File.WriteAllBytes(fileName, attach.Data);
extractFileList.Add(new ZipExtracFile { pkUniqueId = pkUniqueId, fileName = fileName, parentId = extractFileParentId });
if(Path.GetExtension(fileName).ToLower() == ".msg")
{
ExtractMsgFile(fileName, ref pkUniqueId, ref tempPath, lts);
}
}
}
message.Dispose();
This is used to fetch documents from ".msg" file documents , with multilevel ".msg" file and it can download at specific location. For this need to add only MsgReader.dll
I am getting error as mentioned below:
The process cannot access file "E:\TempPDFs\Sample.pdf" because it is being used by another process
I happen to send the pdf from email and after email is sent i need to delete the Sample.pdf file. The code that i have written doesn't work
FileInfo DeleteFileInfo = new FileInfo(directoryPath + "\\" + filename + ".pdf");
if (DeleteFileInfo.Exists)
File.Delete(directoryPath + "\\" + filename + ".pdf");
here directorypath is E:\TempPDFs, filename is Sample
UPDATED:
public static void SendMail(string fromAddress, string[] toAddress, string[] ccAddress, string[] bccAddress, string subject, string messageBody, bool isBodyHtml, ArrayList attachments, string host, string username, string pwd, string port)
{
{
try
{
if (isBodyHtml && !htmlTaxExpression.IsMatch(messageBody))
isBodyHtml = false;
// Create the mail message
MailMessage objMailMsg;
objMailMsg = new MailMessage();
if (toAddress != null)
{
foreach (string toAddr in toAddress)
objMailMsg.To.Add(new MailAddress(toAddr));
}
if (ccAddress != null)
{
foreach (string ccAddr in ccAddress)
objMailMsg.CC.Add(new MailAddress(ccAddr));
}
if (bccAddress != null)
{
foreach (string bccAddr in bccAddress)
objMailMsg.Bcc.Add(new MailAddress(bccAddr));
}
if (fromAddress != null && fromAddress.Trim().Length > 0)
{
//if (fromAddress != null && fromName.trim().length > 0)
// objMailMsg.From = new MailAddress(fromAddress, fromName);
//else
objMailMsg.From = new MailAddress(fromAddress);
}
objMailMsg.BodyEncoding = Encoding.UTF8;
objMailMsg.Subject = subject;
objMailMsg.Body = messageBody;
objMailMsg.IsBodyHtml = isBodyHtml;
if (attachments != null)
{
foreach (string fileName in attachments)
{
if (fileName.Trim().Length > 0 && File.Exists(fileName))
objMailMsg.Attachments.Add(new Attachment(fileName));
}
}
//prepare to send mail via SMTP transport
SmtpClient objSMTPClient = new SmtpClient();
if (objSMTPClient.Credentials != null)
{
}
else
{
objSMTPClient.UseDefaultCredentials = false;
NetworkCredential SMTPUserInfo = new NetworkCredential(username, pwd);
objSMTPClient.Host = host;
objSMTPClient.Port = Int16.Parse(port);
//objSMTPClient.UseDefaultCredentials = false;
objSMTPClient.Credentials = SMTPUserInfo;
//objSMTPClient.EnableSsl = true;
//objSMTPClient.DeliveryMethod = SmtpDeliveryMethod.Network;
}
//objSMTPClient.Host = stmpservername;
//objSMTPClient.Credentials
//System.Net.Configuration.MailSettingsSectionGroup mMailsettings = null;
//string mailHost = mMailsettings.Smtp.Network.Host;
try
{
objSMTPClient.Send(objMailMsg);
}
catch (SmtpException smtpEx)
{
if (smtpEx.Message.Contains("secure connection"))
{
objSMTPClient.EnableSsl = true;
objSMTPClient.Send(objMailMsg);
}
}
}
}
}
let me know if any query
Thanks!
Can we see a code that is responsible for sending a PDF file via e-mail? Your problem might be caused by not released memory stream. If you're using an Attachment class then you should do like the following:
using (Attachment data = new Attachment("document.pdf", MediaTypeNames.Application.Octet))
{
// 1. Adding attachment to the e-mail message
// 2. Sending out the e-mail message
}
The using statement will ensure that the Dispose method is called when the object gets out of the scope.
UPDATE
After calling the Send method make a call to Dispose of your mail message object:
objSMTPClient.Send(objMailMsg);
objMailMsg.Dispose();
Hope this will help you.
or better yet if the object implements IDisposable just write like this
((IDisposable)objSMTPClient).Dispose();