netduino check email - c#

I see lot of examples on how to send email with a but I'm looking to run an action checking an email account.
Does anyone know if that can be done (im sure it can) and point me to some examples?

There are a couple of ways you can get a gmail inbox.
OpenPop
If you do want to just use POP, and you do not mind using external libraries, this looks like the best/easiest way to go. OpenPop allows you to access a secure/unsecure email account and lets you choose the port. See this post to get started.
OpenPop is an open source C#.NET code bundle that implements mail
fetching and parsing. As of this writing, it only uses Microsoft .NET
framework libraries to do the required. But for accessing secure pop
servers, openPop can be extended by using some SSL library.
For example, to access Gmail via Pop:
POPClient poppy = new POPClient();
poppy.Connect("pop.gmail.com", 995, true);
poppy.Authenticate(username#gmail.com, "password");
int Count = poppy.GetMessageCount();
if (Count > 0)
{
for (int i = Count; i >= 1; i -= 1)
{
OpenPOP.MIMEParser.Message m = poppy.GetMessage(i, false);
//use the parsed mail in variable 'm'
}
}
TcpClient POP3:
To retrieve emails from any provider via Pop3, you could use a TcpClient. With Gmail, it is only slightly different, because Gmail uses SSL and port 995 for POP. There is an example of that here:
// create an instance of TcpClient
TcpClient tcpclient = new TcpClient();
// HOST NAME POP SERVER and gmail uses port number 995 for POP
tcpclient.Connect("pop.gmail.com", 995);
// This is Secure Stream // opened the connection between client and POP Server
System.Net.Security.SslStream sslstream = new SslStream(tcpclient.GetStream());
// authenticate as client
sslstream.AuthenticateAsClient("pop.gmail.com");
Gmail Atom Feed:
The first way is to use GmailAtomFeed, which is part of the C# .Net Gmail Tools. The website says:
The GmailAtomFeed class provides a simple object layer for
programmatic access to gmails atom feed. In just a couple lines of
code the feed will be retreived from gmail and parsed. After that the
entries can be accessed through an object layer
AtomFeedEntryCollection, plus access to the raw feed and the feeds
XmlDocument is also available.
And this is an example of how you use it:
// Create the object and get the feed
RC.Gmail.GmailAtomFeed gmailFeed = new RC.Gmail.GmailAtomFeed("username", "password");
gmailFeed.GetFeed();
// Access the feeds XmlDocument
XmlDocument myXml = gmailFeed.FeedXml
// Access the raw feed as a string
string feedString = gmailFeed.RawFeed
// Access the feed through the object
string feedTitle = gmailFeed.Title;
string feedTagline = gmailFeed.Message;
DateTime feedModified = gmailFeed.Modified;
//Get the entries
for(int i = 0; i < gmailFeed.FeedEntries.Count; i++) {
entryAuthorName = gmailFeed.FeedEntries[i].FromName;
entryAuthorEmail = gmailFeed.FeedEntries[i].FromEmail;
entryTitle = gmailFeed.FeedEntries[i].Subject;
entrySummary = gmailFeed.FeedEntries[i].Summary;
entryIssuedDate = gmailFeed.FeedEntries[i].Received;
entryId = gmailFeed.FeedEntries[i].Id;
}
IMAP
Another way, if you are not LIMITED to POP, is to use IMAP. With IMAP, you can connect to a SSL server and choose a port along with that:
using (Imap imap = new Imap())
{
imap.ConnectSSL("imap.gmail.com", 993);
imap.Login("angel_y#company.com", "xyx***"); // MailID As Username and Password
imap.SelectInbox();
List<long> uids = imap.SearchFlag(Flag.Unseen);
foreach (long uid in uids)
{
string eml = imap.GetMessageByUID(uid);
IMail message = new MailBuilder()
.CreateFromEml(eml);
Console.WriteLine(message.Subject);
Console.WriteLine(message.TextDataString);
}
imap.Close(true);
}

I found this code online but "POP3_Client" isn't recognized and I don't see any refrences to add it
POP3_Client Mailbox = new POP3_Client(new >>>>IntegratedSocket<<<<<("pop.yourisp.com", 110), "yourusername", "yourpassword");
Mailbox.Connect();
Debug.Print("Message count: " + Mailbox.MessageCount.ToString());
Debug.Print("Box size in bytes: " + Mailbox.BoxSize.ToString());
uint[] Id, Size;
Mailbox.ListMails(out Id, out Size);
for (int Index = 0; Index < Id.Length; ++Index)
{
string[] Headers = Mailbox.FetchHeaders(Id[Index], new string[] { "subject", "from", "date" });
Debug.Print("Mail ID " + Id[Index].ToString() + " is " + Size[Index].ToString() + " bytes");
Debug.Print("Subject: " + Headers[0]);
Debug.Print("From: " + Headers[1]);
Debug.Print("Date: " + Headers[2]);
Debug.Print("======================================================================");
}
Mailbox.Close();

Related

How can I detect if my fetched email is bounced or not

I fetched emails from servers by using IMAP or POP3 and entered the fetched emails to database but I noticed there are a lot of bounced emails entered to the system so I searched a lot on google to check fetched email and if it's bounced email I'll not enter it to the system and I found library BounceDetectResult to detect if email is bounced or not but this library working only with message type MimeMessage so It's useful when I use IMAP but it's not work with message type OpenPop.Mime.Message so I can't use It when I use POP3
var result= BounceDetectorMail.Detect(message);//message type MimeMessage
if (result.IsBounce)
{
em.DelivaryFailure = true;
}
so my problem I didn't find way to detect if my retrieved message is bounced or not when I use pop3 in retrieving
It looks like the MailBounceDetector library that you mentioned uses my MimeKit library to detect if a message is a bounced message or not.
The good news is that you can use that library because I also have a library that does POP3 called MailKit, so you can use that instead of OpenPOP.NET.
For any who may need, from Bounce inspector software library, supports both POP3 and IMAP:
// POP3 server information.
const string serverName = "myserver";
const string user = "name#domain.com";
const string password = "mytestpassword";
const int port = 995;
const SecurityMode securityMode = SecurityMode.Implicit;
// Create a new instance of the Pop3Client class.
Pop3Client client = new Pop3Client();
Console.WriteLine("Connecting Pop3 server: {0}:{1}...", serverName, port);
// Connect to the server.
client.Connect(serverName, port, securityMode);
// Login to the server.
Console.WriteLine("Logging in as {0}...", user);
client.Authenticate(user, password);
// Initialize BounceInspector.
BounceInspector inspector = new BounceInspector();
inspector.AllowInboxDelete = false; // true if you want BounceInspector automatically delete all hard bounces.
// Register processed event handler.
inspector.Processed += inspector_Processed;
// Download messages from Pop3 Inbox to 'c:\test' and process them.
BounceResultCollection result = inspector.ProcessMessages(client, "c:\\test");
// Display processed emails.
foreach (BounceResult r in result)
{
// If this message was identified as a bounced email message.
if (r.Identified)
{
// Print out the result
Console.Write("FileName: {0}\nSubject: {1}\nAddress: {2}\nBounce Category: {3}\nBounce Type: {4}\nDeleted: {5}\nDSN Action: {6}\nDSN Diagnostic Code: {7}\n\n",
System.IO.Path.GetFileName(r.FilePath),
r.MailMessage.Subject,
r.Addresses[0],
r.BounceCategory.Name,
r.BounceType.Name,
r.FileDeleted,
r.Dsn.Action,
r.Dsn.DiagnosticCode);
}
}
Console.WriteLine("{0} bounced message found", result.BounceCount);
// Disconnect.
Console.WriteLine("Disconnecting...");
client.Disconnect();

Find emails by message Id using using IMAP and MailSystem.NET

I'm using IMAP and MailSystem.NET to read emails in c#. How do I search emails by message id? (msg.MessageId)
using (Imap4Client imap = new Imap4Client()){
imap.ConnectSsl(protocol, port);
imap.LoginFast(email, password);
Mailbox inbox = imap.SelectMailbox("INBOX");
int[] mails= inbox.Search("UNSEEN");
for (int i = 0; i < mailsUnread.Length; i++) {
Message msg = inbox.Fetch.MessageObject(mailsUnread[i]);
string subject = msg.Subject;
string body = msg.BodyText.Text;
string messageId= msg.MessageId;
}
}
Thanks
I would highly recommend using MailKit instead as it is a much much much more robust IMAP client library than MailSystem.NET... but...
The way you would search for messages based on the Message-Id header in MailSystem.NET is:
int[] mails = inbox.Search (string.Format ("HEADER \"MESSAGE-ID\" \"{0}\"", msg.MessageId));
Hope that helps.

Sending email to multiple recipients via Google

I am working on an C# project where I am building my own SMTP server. It is basically working but I am now trying to get multiple recipients being sent but I am receiving an error.
I am getting the MX record from the senders domain and I am then using MX Record to try and send an email to multiple recipients. If I do two recipients with the same domain it works fine, if the two recipients have different domains, I then get the following response:
Failed to send email. General Exception: Error in processing. The server response was: 4.3.0 Multiple destination domains per transaction is unsupported. Please
There is nothing after please that's the end of the response.
Below is how I am getting the MX Record:
string[] mxRecords = mxLookup.getMXRecords(Classes.CommonTasks.getDomainFromEmail(domain));
public string[] getMXRecords(string domain)
{
DnsLite dl = new DnsLite(library);
ArrayList dnsServers = getDnsServers();
dl.setDnsServers(dnsServers);
ArrayList results = null;
string[] retVal = null;
results = dl.getMXRecords(domain);
if (results != null)
{
retVal = new string[results.Count];
int counter = 0;
foreach (MXRecord mx in results)
{
retVal[counter] = mx.exchange.ToString();
counter++;
}
}
return retVal;
}
Below is how I am sending the email.
if (mxRecords != null)
{
MailMessage composedMail = new MailMessage();
composedMail.From = new MailAddress(message.EmailFromAddress);
//MailAddressCollection test = new MailAddressCollection();
//composedMail.To = test;
composedMail = addRecipientsToEmail(composedMail, message.emailRecipients);
composedMail.Subject = message.subject;
composedMail.Body = message.EmailBody;
if (message.contentType.ToString().Contains("text/html"))
{
composedMail.IsBodyHtml = true;
}
SmtpClient smtp = new SmtpClient(mxRecords[0]);
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Port = 25;
if (Configuration.emailConfig.useSmtpMaxIdleTime)
{
smtp.ServicePoint.MaxIdleTime = 1;
}
library.logging(methodInfo, string.Format("Sending email via MX Record: {0}", mxRecords[0]));
smtp.Send(composedMail);
updateEmailStatus(message.emailID, EmailStatus.Sent);
library.logging(methodInfo, string.Format("Successfully sent email ID: {0}", message.emailID));
}
else
{
string error = string.Format("No MX Record found for domain: {0}", domain);
library.logging(methodInfo, error);
library.setAlarm(error, CommonTasks.AlarmStatus.Warning, methodInfo);
}
This looks as if it is something that Google is restricting from being done but I can't find a way to work around out, other than to send the emails separately for each recipient.
If it's of any use, the two domains are google app domains.
Thanks for any help you can provide.
It seems you are not alone. Check this out.
:
"Based on my investigation and research, I believe what's happening is your system is connecting directly to the delivery server (aspmx.l.google.com). As this is the delivery server, it does not allow:
Delivery to accounts that are not provisioned on Google (i.e., unauthenticated relaying).
Delivery to multiple different domains within the same SMTP session.
The second one is the one that is important to us. As of the beginning of this month(May2012), adjustments were made to our server settings that mean that our delivery server is strictly enforcing the multiple-domain-not-allowed rule. There are two ways to get around this. The first is to send to separate domains on separate smtp sessions, and the second is to use smtp.gmail.com in place of aspmx.l.google.com."
http://productforums.google.com/forum/#!topic/apps/jEUrvTd1S_w
Sine you can send an email with a single recipient through google your issue is not in resolving the mx-record. The Mx record tells an IP-address but doesn't tell about the functionality/behavior of the service behind that ip.
You can resolve the mx-record, so far so good. But you don't need to to resolve the mx on your own as the smtp-client does it on your behalve, just supllying the hostname will do. But note that this was a great excersise to learn more about DNS. No time waste :-)
As far as I recall, sending mail through google in the way you intend you need a google account. Authenticate with the smtp-server with the credentials for that account can open a new perspective

Transfer content of email to C# page

I have created one web-form that contains controls to add name, date of birth, gender info of user with add button, once add button clicked that info goes to database.
But i have my mailbox, for eg. gmail some mails are coming in inbox that contains info same as earlier(Name, Date of birth, gender etc.). So can i have functionality to transfer that inbox data to my database?
Yes - you can.
There are a lot of libraries that you can leverage to make it trivial to check a Gmail account. Here is just one: http://sourceforge.net/projects/hpop/
Here is sample code for fetching all of your e-mails:
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;
}
}
You'll still need to go through each one and determine if it's valid for your database and then grab the data and insert it into the database; but it should be pretty straight-forward (and almost identical to what you are already doing)
For GMail you can use the following to get your mail:
List<Message> myMail = FetchAllMessages("pop.gmail.com", 995, true, "MyEmail#gmail.com", "mysupersecretpasswordshhhhh!");

using c# .net libraries to check for IMAP messages from gmail servers [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Does anyone have any sample code in that makes use of the .Net framework that connects to googlemail servers via IMAP SSL to check for new emails?
I'd recommend looking at MailKit as it is probably the most robust mail library out there and it's Open Source (MIT).
One of the awesome things about MailKit is that all network APIs are cancelable (something I haven't seen available in any other IMAP library).
It's also the only library that I know of that supports threading of messages.
using System;
using System.Net;
using System.Threading;
using MailKit.Net.Imap;
using MailKit.Search;
using MailKit;
using MimeKit;
namespace TestClient {
class Program
{
public static void Main (string[] args)
{
using (var client = new ImapClient ()) {
using (var cancel = new CancellationTokenSource ()) {
client.Connect ("imap.gmail.com", 993, true, cancel.Token);
// If you want to disable an authentication mechanism,
// you can do so by removing the mechanism like this:
client.AuthenticationMechanisms.Remove ("XOAUTH");
client.Authenticate ("joey", "password", cancel.Token);
// The Inbox folder is always available...
var inbox = client.Inbox;
inbox.Open (FolderAccess.ReadOnly, cancel.Token);
Console.WriteLine ("Total messages: {0}", inbox.Count);
Console.WriteLine ("Recent messages: {0}", inbox.Recent);
// download each message based on the message index
for (int i = 0; i < inbox.Count; i++) {
var message = inbox.GetMessage (i, cancel.Token);
Console.WriteLine ("Subject: {0}", message.Subject);
}
// let's try searching for some messages...
var query = SearchQuery.DeliveredAfter (DateTime.Parse ("2013-01-12"))
.And (SearchQuery.SubjectContains ("MailKit"))
.And (SearchQuery.Seen);
foreach (var uid in inbox.Search (query, cancel.Token)) {
var message = inbox.GetMessage (uid, cancel.Token);
Console.WriteLine ("[match] {0}: {1}", uid, message.Subject);
}
client.Disconnect (true, cancel.Token);
}
}
}
}
}
The URL listed here might be of interest to you
http://www.codeplex.com/InterIMAP
which was extension to
http://www.codeproject.com/KB/IP/imaplibrary.aspx?fid=91819&df=90&mpp=25&noise=5&sort=Position&view=Quick&fr=26&select=2562067#xx2562067xx
As the author of the above project i can say that yes it does support SSL.
I am currently working on a new version of the library that will be completely asynchronous to increase the speed with which it can interact with IMAP servers.
That code, while not complete, can be downloaded, along with the original synchronous library (which also supports SSL), from the code plex site linked to above.
Cross posted from the other similar question. See what happens when they get so similar?
I've been searching for an IMAP solution for a while now, and after trying quite a few, I'm going with AE.Net.Mail.
There is no documentation, which I consider a downside, but I was able to whip this up by looking at the source code (yay for open source!) and using Intellisense. The below code connects specifically to Gmail's IMAP server:
// Connect to the IMAP server. The 'true' parameter specifies to use SSL
// which is important (for Gmail at least)
ImapClient ic = new ImapClient("imap.gmail.com", "name#gmail.com", "pass",
ImapClient.AuthMethods.Login, 993, true);
// Select a mailbox. Case-insensitive
ic.SelectMailbox("INBOX");
Console.WriteLine(ic.GetMessageCount());
// Get the first *11* messages. 0 is the first message;
// and it also includes the 10th message, which is really the eleventh ;)
// MailMessage represents, well, a message in your mailbox
MailMessage[] mm = ic.GetMessages(0, 10);
foreach (MailMessage m in mm)
{
Console.WriteLine(m.Subject);
}
// Probably wiser to use a using statement
ic.Dispose();
I'm not affiliated with this library or anything, but I've found it very fast and stable.
Lumisoft.net has both IMAP client and server code that you can use.
I've used it to download email from Gmail. The object model isn't the best, but it is workable, and seems to be rather flexible and stable.
Here is the partial result of my spike to use it. It fetches the first 10 headers with envelopes, and then fetches the full message:
using (var client = new IMAP_Client())
{
client.Connect(_hostname, _port, _useSsl);
client.Authenticate(_username, _password);
client.SelectFolder("INBOX");
var sequence = new IMAP_SequenceSet();
sequence.Parse("0:10");
var fetchItems = client.FetchMessages(sequence, IMAP_FetchItem_Flags.Envelope | IMAP_FetchItlags.UID,
false, true);
foreach (var fetchItem in fetchItems)
{
Console.Out.WriteLine("message.UID = {0}", fetchItem.UID);
Console.Out.WriteLine("message.Envelope.From = {0}", fetchItem.Envelope.From);
Console.Out.WriteLine("message.Envelope.To = {0}", fetchItem.Envelope.To);
Console.Out.WriteLine("message.Envelope.Subject = {0}", fetchItem.Envelope.Subject);
Console.Out.WriteLine("message.Envelope.MessageID = {0}", fetchItem.Envelope.MessageID);
}
Console.Out.WriteLine("Fetching bodies");
foreach (var fetchItem in client.FetchMessages(sequence, IMAP_FetchItem_Flags.All, false, true)
{
var email = LumiSoft.Net.Mail.Mail_Message.ParseFromByte(fetchItem.MessageData);
Console.Out.WriteLine("email.BodyText = {0}", email.BodyText);
}
}
There is no .NET framework support for IMAP. You'll need to use some 3rd party component.
Try Mail.dll email component, it's very affordable and easy to use, it also supports SSL:
using(Imap imap = new Imap())
{
imap.ConnectSSL("imap.company.com");
imap.Login("user", "password");
imap.SelectInbox();
List<long> uids = imap.Search(Flag.Unseen);
foreach (long uid in uids)
{
string eml = imap.GetMessageByUID(uid);
IMail message = new MailBuilder()
.CreateFromEml(eml);
Console.WriteLine(message.Subject);
Console.WriteLine(message.Text);
}
imap.Close(true);
}
Please note that this is a commercial product I've created.
You can download it here: https://www.limilabs.com/mail.
MailSystem.NET contains all your need for IMAP4. It's free & open source.
(I'm involved in the project)
the source to the ssl version of this is here: http://atmospherian.wordpress.com/downloads/
Another alternative: HigLabo
https://higlabo.codeplex.com/documentation
Good discussion: https://higlabo.codeplex.com/discussions/479250
//====Imap sample================================//
//You can set default value by Default property
ImapClient.Default.UserName = "your server name";
ImapClient cl = new ImapClient("your server name");
cl.UserName = "your name";
cl.Password = "pass";
cl.Ssl = false;
if (cl.Authenticate() == true)
{
Int32 MailIndex = 1;
//Get all folder
List<ImapFolder> l = cl.GetAllFolders();
ImapFolder rFolder = cl.SelectFolder("INBOX");
MailMessage mg = cl.GetMessage(MailIndex);
}
//Delete selected mail from mailbox
ImapClient pop = new ImapClient("server name", 110, "user name", "pass");
pop.AuthenticateMode = Pop3AuthenticateMode.Pop;
Int64[] DeleteIndexList = new.....//It depend on your needs
cl.DeleteEMail(DeleteIndexList);
//Get unread message list from GMail
using (ImapClient cl = new ImapClient("imap.gmail.com"))
{
cl.Port = 993;
cl.Ssl = true;
cl.UserName = "xxxxx";
cl.Password = "yyyyy";
var bl = cl.Authenticate();
if (bl == true)
{
//Select folder
ImapFolder folder = cl.SelectFolder("[Gmail]/All Mail");
//Search Unread
SearchResult list = cl.ExecuteSearch("UNSEEN UNDELETED");
//Get all unread mail
for (int i = 0; i < list.MailIndexList.Count; i++)
{
mg = cl.GetMessage(list.MailIndexList[i]);
}
}
//Change mail read state as read
cl.ExecuteStore(1, StoreItem.FlagsReplace, "UNSEEN")
}
//Create draft mail to mailbox
using (ImapClient cl = new ImapClient("imap.gmail.com"))
{
cl.Port = 993;
cl.Ssl = true;
cl.UserName = "xxxxx";
cl.Password = "yyyyy";
var bl = cl.Authenticate();
if (bl == true)
{
var smg = new SmtpMessage("from mail address", "to mail addres list"
, "cc mail address list", "This is a test mail.", "Hi.It is my draft mail");
cl.ExecuteAppend("GMail/Drafts", smg.GetDataText(), "\\Draft", DateTimeOffset.Now);
}
}
//Idle
using (var cl = new ImapClient("imap.gmail.com", 993, "user name", "pass"))
{
cl.Ssl = true;
cl.ReceiveTimeout = 10 * 60 * 1000;//10 minute
if (cl.Authenticate() == true)
{
var l = cl.GetAllFolders();
ImapFolder r = cl.SelectFolder("INBOX");
//You must dispose ImapIdleCommand object
using (var cm = cl.CreateImapIdleCommand()) Caution! Ensure dispose command object
{
//This handler is invoked when you receive a mesage from server
cm.MessageReceived += (Object o, ImapIdleCommandMessageReceivedEventArgs e) =>
{
foreach (var mg in e.MessageList)
{
String text = String.Format("Type is {0} Number is {1}", mg.MessageType, mg.Number);
Console.WriteLine(text);
}
};
cl.ExecuteIdle(cm);
while (true)
{
var line = Console.ReadLine();
if (line == "done")
{
cl.ExecuteDone(cm);
break;
}
}
}
}
}
LumiSoft.ee - works great, fairly easy. Compiles with .NET 4.0.
Here are the required links to their lib and examples.
Downloads Main:
http://www.lumisoft.ee/lsWWW/Download/Downloads/
Code Examples:
are located here: ...lsWWW/Download/Downloads/Examples/
.NET:
are located here: ...lsWWW/Download/Downloads/Net/
I am putting a SIMPLE sample up using their lib on codeplex (IMAPClientLumiSoft.codeplex.com). You must get their libraries directly from their site. I am not including them because I don't maintain their code nor do I have any rights to the code. Go to the links above and download it directly. I set LumiSoft project properties in my VS2010 to build all of it in .NET 4.0 which it did with no errors.
Their samples are fairly complex and maybe even overly tight coding when just an example. Although I expect that these are aimed at advanced level developers in general.
Their project worked with minor tweaks. The tweaks: Their IMAP Client Winform example is set in the project properties as "Release" which prevents VS from breaking on debug points. You must use the solution "Configuration Manager" to set the project to "Active(Debug)" for breakpoints to work. Their examples use anonymous methods for event handlers which is great tight coding... not real good as a teaching tool. My project uses "named" event method handlers so you can set breakpoints inside the handlers. However theirs is an excellent way to handle inline code. They might have used the newer Lambda methods available since .NET 3.0 but did not and I didn't try to convert them.
From their samples I simplified the IMAP client to bare minimum.

Categories