How to read mail content through c# console application - c#

MailRepository rep = new MailRepository("imap.mail.yahoo.com", 993, true, #"xxxxx#yahoo.com", "*******");
foreach (Message email in rep.GetUnreadMails("Inbox"))
{
//Console.WriteLine(string.Format("<p>{0}: {1}</p><p>{2}</p>", email.From, email.Subject, email.BodyHtml.Text));
Console.WriteLine(email.From);
Console.WriteLine(email.Subject);
Console.WriteLine(email.BodyHtml.Text);
if (email.Attachments.Count > 0)
{
foreach (MimePart attachment in email.Attachments)
{
Console.WriteLine(string.Format("<p>Attachment: {0} {1}</p>", attachment.ContentName, attachment.ContentType.MimeType));
}
}
}
Above is my code, which is used to read mail content. It's working fine when i tryed for gmail port, but while going for yahoo or some other. It's not allowing me to read the mail throwing exception. Is there any other source . Please guide me

First, check your credentials are correct.
Second, put a try catch in the constructor to see if you can get more info about the unhandled exception:
public MailRepository(string mailServer, int port, bool ssl, string login, string password)
{
try {
if (ssl) {
Client.ConnectSsl(mailServer, port);
}
else {
Client.Connect(mailServer, port);
}
Client.Login(login, password);
}
catch(Exception ex)
{
//Check the exception details here
}
}
Third, the origin of the MailRepository class appears to be from here that uses the Imap4Client implementation which others have complained doesn't work with Yahoo:
Connecting to yahoo email with IMAP4 MailSystem.NET
The accepted answer recommends using ImapX 2 - crossplatform IMAP library for .NET to handle GMail, Yahoo, etc.

Related

Read/Retrieve emails from Outlook (Office 365) account

I set up my outlook Office 365 account and I want to retrieve the emails from my outlook mailbox, earlier we were using Exchange Service in our code, but now we can't use the Exchange service anymore due to EWS his no longer available in microsoft.
Could you please help me how can I retrieve my emails in outlook office 365 account.
I am attaching a sample code that I have created but I am not able to read the emails.
In the below code, i tried to retrieve email through IMAP4 protocol server.
When i run the code, i get this error - ReceiveOutlookMail.exe' has exited with code 0 (0x0).
class Program
{
// Generate an unqiue email file name based on date time
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
{
// Create a folder named "inbox" under current directory
// to save the email retrieved.
string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory());
// If the folder is not existed, create it.
if (!Directory.Exists(localInbox))
{
Directory.CreateDirectory(localInbox);
}
// Hotmail/MSN IMAP4 server is "imap-mail.outlook.com"
//MailServer oServer = new MailServer("imap-server-name",
// "liveid#hotmail.com", "yourpassword", ServerProtocol.Imap4);
// For office 365 user, please change server to:
MailServer oServer = new MailServer("imap-server-name",
"test#gmail.com", "password", ServerProtocol.Imap4);
// Enable SSL connection.
oServer.SSLConnection = true;
// Set 993 SSL port
oServer.Port = 993;
MailClient oClient = new MailClient("TryIt");
oClient.Connect(oServer);
// retrieve unread/new email only
oClient.GetMailInfosParam.Reset();
oClient.GetMailInfosParam.GetMailInfosOptions = GetMailInfosOptionType.NewOnly;
MailInfo[] infos = oClient.GetMailInfos();
Console.WriteLine("Total {0} unread email(s)\r\n", infos.Length);
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);
// Receive email from IMAP4 server
Mail oMail = oClient.GetMail(info);
Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);
// Generate an unqiue email file name based on date time.
string fileName = _generateFileName(i + 1);
string fullPath = string.Format("{0}\\{1}", localInbox, fileName);
// Save email to local disk
oMail.SaveAs(fullPath, true);
// mark unread email as read, next time this email won't be retrieved again
if (!info.Read)
{
oClient.MarkAsRead(info, true);
}
// if you don't want to leave a copy on server, please use
// oClient.Delete(info);
// instead of MarkAsRead
}
// Quit and expunge emails marked as deleted from IMAP4 server.
oClient.Quit();
Console.WriteLine("Completed!");
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}

How to add attachments to mailto in c#?

string email ="sample#gmail.com";
attachment = path + "/" + filename;
Application.OpenURL ("mailto:" +
email+"
?subject=EmailSubject&body=EmailBody"+"&attachment="+attachment);
In the above code, attachment isn't working. Is there any other alternative to add attachments using a mailto: link in C#?
mailto: doesn't officially support attachments. I've heard Outlook 2003 will work with this syntax:
<a href='mailto:name#domain.com?Subject=SubjTxt&Body=Bod_Txt&Attachment=""C:\file.txt"" '>
Your problem has already been answered:
c-sharp-mailto-with-attachment
You can use the System.Net.Mail which has the MailMessage.Attachments Property. Something like:
message.Attachments.Add(new Attachment(yourAttachmentPath));
OR
You can try like this:
using SendFileTo;
namespace TestSendTo
{
public partial class Form1 : Form
{
private void btnSend_Click(object sender, EventArgs e)
{
MAPI mapi = new MAPI();
mapi.AddAttachment("c:\\temp\\file1.txt");
mapi.AddAttachment("c:\\temp\\file2.txt");
mapi.AddRecipientTo("person1#somewhere.com");
mapi.AddRecipientTo("person2#somewhere.com");
mapi.SendMailPopup("testing", "body text");
// Or if you want try and do a direct send without displaying the
// mail dialog mapi.SendMailDirect("testing", "body text");
}
}
}
The above code uses the MAPI32.dll.
Source
It probably won't attach the document because you are at the liberty
of the email client to implement the mailto protocol and include
parsing for the attachment clause. You may not know what mail client
is installed on the PC, so it may not always work - Outlook certainly
doesn't support attachments using mailto.
A better way to handle this is to send the mail on the server using System.Net.Mail.Attachment.
public static void CreateMessageWithAttachment(string server)
{
// Specify the file to be attached and sent.
// This example assumes that a file named Data.xls exists in the
// current working directory.
string file = "data.xls";
// Create a message and set up the recipients.
MailMessage message = new MailMessage(
"jane#contoso.com",
"ben#contoso.com",
"Quarterly data report.",
"See the attached spreadsheet.");
// Create the file attachment for this e-mail message.
Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
// Add time stamp information for the file.
ContentDisposition disposition = data.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(file);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
// Add the file attachment to this e-mail message.
message.Attachments.Add(data);
//Send the message.
SmtpClient client = new SmtpClient(server);
// Add credentials if the SMTP server requires them.
client.Credentials = CredentialCache.DefaultNetworkCredentials;
try
{
client.Send(message);
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in CreateMessageWithAttachment(): {0}", ex.ToString());
}
data.Dispose();
}

Move email to another folder with OpenPop

How I can to move emails from inbox to some folder, for example folder "test"
Pop3Client client = new Pop3Client()
client contains method to get email in html, xml, etc. also delete email or delete all emails, but I need to move some email to another folder, it is possible ?
OpenPop implements the POP3 protocol. This protocol is old, and does not know about such things as folders. Therefore, the OpenPop implementation cannot handle folders as well.
If you need to use folders, consider using some IMAP client instead. IMAP is a newer and more modern protocol.
As J. Steen has pointed out. No, you can't with OpenPop.
Just encase you still want to do it and it wasn't a purely academic question. Taken from MSDN
How to: Programmatically Move Items in Outlook
This example moves unread e-mail messages from the Inbox to a folder named Test. The example only moves messages that have the word Test in the Subject field.
Applies to: The information in this topic applies to application-level projects for Outlook 2013 and Outlook 2010. For more information, see Features Available by Office Application and Project Type.
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
this.Application.NewMail += new Microsoft.Office.Interop.Outlook.
ApplicationEvents_11_NewMailEventHandler
(ThisAddIn_NewMail);
}
private void ThisAddIn_NewMail()
{
Outlook.MAPIFolder inBox = (Outlook.MAPIFolder)this.Application.
ActiveExplorer().Session.GetDefaultFolder
(Outlook.OlDefaultFolders.olFolderInbox);
Outlook.Items items = (Outlook.Items)inBox.Items;
Outlook.MailItem moveMail = null;
items.Restrict("[UnRead] = true");
Outlook.MAPIFolder destFolder = inBox.Folders["Test"];
foreach (object eMail in items)
{
try
{
moveMail = eMail as Outlook.MailItem;
if (moveMail != null)
{
string titleSubject = (string)moveMail.Subject;
if (titleSubject.IndexOf("Test") > 0)
{
moveMail.Move(destFolder);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}

Auth fail error when using SharpSSH

I am trying to connect to a Solaris/Unix server using a C# class to read system information/configuration, memory usage etc.
My requirement is to run the commands on the server from a C# application (as we do with a PuTTY client) and store the response in a string variable for later processing.
After some research, I found out that SharpSSH library can be used to do the same.
When I try to run my code, the following line gives me an Auth Fail exception.
I am confident that the credentials (server name, user name and password) are correct since I am able to log-in from the PuTTY client with the same credentials.
SshStream ssh = new SshStream(servername, username, password);
What am I doing wrong?
The following is the stack trace if it helps!
at Tamir.SharpSsh.jsch.Session.connect(Int32 connectTimeout)
at Tamir.SharpSsh.jsch.Session.connect()
at Tamir.SharpSsh.SshStream..ctor(String host, String username, String password)
After some research, I found a VB code which pointed me to the right direction. It seems that adding an additional event handler for the KeyboardInteractiveAuthenticationMethod helped to solve this. Hope this helps someone else.
void HandleKeyEvent(Object sender, AuthenticationPromptEventArgs e)
{
foreach (AuthenticationPrompt prompt in e.Prompts)
{
if (prompt.Request.IndexOf("Password:", StringComparison.InvariantCultureIgnoreCase) != -1)
{
prompt.Response = password;
}
}
}
private bool connectToServer()
{
try
{
KeyboardInteractiveAuthenticationMethod kauth = new KeyboardInteractiveAuthenticationMethod(username);
PasswordAuthenticationMethod pauth = new PasswordAuthenticationMethod(username, password);
kauth.AuthenticationPrompt += new EventHandler<AuthenticationPromptEventArgs>(HandleKeyEvent);
ConnectionInfo connectionInfo = new ConnectionInfo(serverName, port, username, pauth, kauth);
sshClient = new SshClient(connectionInfo);
sshClient.Connect();
return true;
}
catch (Exception ex)
{
if (null != sshClient && sshClient.IsConnected)
{
sshClient.Disconnect();
}
throw ex;
}
}

System.Net.Mail.SmtpException: Insufficient system storage. The server response was: 4.3.1 Insufficient system resources

I've recently designed a program in C# that will pull information from SQL databases, write an HTML page with the results, and auto-email it out. I've got everything working [sporadically], the problem I'm having is that I seem to be crashing our company's exchange server. After the first few successful runs of the program, I'll start getting this exception:
Base exception: System.Net.Mail.SmtpException: Insufficient system storage. The server response was: 4.3.1 Insufficient system resources
I'm wondering if I should be calling some sort of Dispose()-like method in my mailing? Or if there is any other apparent reason that I would be causing the mail system to stop responding? This affects all clients in our company, not just my code.
This is Exchange 2010, and my code is compiled against .NET 3.5. My attachments are typically 27kb. If I log into the exchange server, it seems that messages just stick in a queue indefinitely. Clearing out the queue (remove without sending NDR) and rebooting the server will get it going again.
The mailing portions look like this (username, password, and address changed):
public void doFinalEmail()
{
List<string> distList = new List<string>();
string distListPath = Environment.CurrentDirectory + "\\DistList.txt";
string aLine;
logThat("Attempting email distribution of the generated report.");
if (File.Exists(distListPath))
{
FileInfo distFile = new FileInfo(distListPath);
StreamReader distReader = distFile.OpenText();
while (!String.IsNullOrEmpty(aLine = distReader.ReadLine()))
{
distList.Add(aLine);
}
}
else
{
logThat("[[ERROR]]: Distribution List DOES NOT EXIST! Path: " + distListPath);
}
MailMessage msg = new MailMessage();
MailAddress fromAddress = new MailAddress("emailaddresshere");
msg.From = fromAddress;
logThat("Recipients: ");
foreach (string anAddr in distList)
{
msg.To.Add(anAddr);
logThat("\t" + anAddr);
}
if (File.Exists(Program.fullExportPath))
{
logThat("Attachment: " + Program.fullExportPath);
Attachment mailAttachment = new Attachment(Program.fullExportPath);
msg.Attachments.Add(mailAttachment);
string subj = "Company: " + Program.yestFileName;
msg.Subject = subj;
msg.IsBodyHtml = true;
msg.BodyEncoding = System.Text.Encoding.UTF8;
sendMail(msg);
}
else
{
logThat("[[ERROR]]: ATTACHMENT DOES NOT EXIST! Path: " + Program.fullExportPath);
}
}
public void sendMail(MailMessage msg)
{
try
{
string username = "user"; //domain user
string password = "pass"; // password
SmtpClient mClient = new SmtpClient();
mClient.Host = "192.168.254.11";
mClient.Credentials = new NetworkCredential(username, password);
mClient.DeliveryMethod = SmtpDeliveryMethod.Network;
mClient.Send(msg);
}
catch (Exception oops)
{
string whatHappened = String.Format("Company: \r\nFailure in {0}! \r\n\r\nError message: {1} \r\nError data: {2} \r\n\r\nStack trace: {3} \r\n\r\nBase exception: {4} \r\nOccuring in method: {5} with a type of {6}\r\n", oops.Source, oops.Message, oops.Data, oops.StackTrace, oops.GetBaseException(), oops.TargetSite, oops.GetType());
logThat(whatHappened);
Environment.Exit(1);
}
}
This error can happen when:
The exchange server is out of disk space.
The recipient mailbox is out of disk space.
It is more common to run into issue #2 than issue #1.
Here is a list of Exchange Status Codes and their meanings.
To narrow down the issue definitively, you could swap in a different mail client like aspNetEmail (you can get an eval version to test), it wouldn't take but a few lines of code. If the problem persists, it is on the server; if not, it is on the client. I would strongly suspect this is a problem on the server, however, as when the client closes the connection and the message is sent, the server should really not be holding any resources as a result of that connection. You could verify this by looking at your SMTP logs and making sure there was no SMTP error when the connection was closed.
If this is indeed a problem on the server (the SMTP log shows clean disconnection and the problem is replicable with an alternate client), then I would log onto the server (if you can get access), and watch the disk space as jeuton suggests.
In exchange 2007 the c: (system drive) needs about 4GB of free disk space. This was our problem. Increment the drive and the mails will flow again.

Categories