I am trying to move a message to another folder in a mail box using the IMAP functionality of ae.net.mail. The problem is that although the message is moved into the target folder, it is not removed from INBOX.
I'm also having a problem deleting a message. In this case I'm finding that the status of the message merely changes from unseen to seen.
Here is what I have tried:
using (ImapClient ic = new ImapClient(
host, email, password, ImapClient.AuthMethods.Login, 993, true))
{
ic.SelectMailbox("INBOX");
string[] uids = ic.Search(SearchCondition.From("someone#gmail.com"));
MailMessage[] messages =
ic.GetMessages(uids[0], uids[uids.Length - 1], false);
ic.MoveMessage(uids[0], "Junk");
}
The standard IMAP protocol does not have a MOVE command (but there is an extension that adds it). So, depending on your IMAP server, the client may need to implement MOVE as a UID COPY + UID STORE +FLAGS.SILENT (\Deleted) + UID EXPUNGE, but that assumes that the server supports the UIDPLUS extension. If the server doesn't support UIDPLUS, either, then it becomes essentially impossible to implement properly. All you can do is COPY + STORE +FLAGS.SILENT (\Deleted) but cannot do the EXPUNGE because there's no way to limit the messages that will get expunged (I suppose you could unmark any other deleted messages, then EXPUNGE, then re-mark them as \Deleted, but that starts to become risky).
This would explain why the messages might still exist in the INBOX (although they should be at least marked as deleted).
Not sure why marking a message as deleted is marking it as Seen. That seems like a bug in AE.NET.Mail.
Related
I'm moving messages from the inbox folder to a new folder. After a while I need to move some of these messages(not all) to a new folder. The problem with this is that everytime I move a message the uid changes. How can I do this without moving the wrong message?
If your server supports UIDPLUS (nearly all do), and you yourself are moving or copying the messages, the server will give you the new UID when you copy or move it in the COPYUID response. You'll need to record this.
An example from the IMAP MOVE RFC6851:
C: a UID MOVE 42:69 foo
S: * OK [COPYUID 432432 42:69 1202:1229]
S: * 22 EXPUNGE
S: (more expunges)
S: a OK Done
The COPYUID response includes the UIDVALIDITY of the destination mail box, the UID set of the source messages, and the UID set of the destination messages.
If some other process is doing the moving, there's no way to guarantee the same message, and you'd have to track them based on their content (eg, the Message-ID header, the date time, a hash, etc.)
You're "moving" also involves an INSERT into DB to keep track of UIDs? If yes, watch for autogenerated PKs.
I am currently working on a former colleague's project that deals with saving emails from Exchange to our ERP system.
But I have run into a strange problem. Sometimes when the system receives an email, that contains an email as an attachment. It throws an error because the DataTimeReceived date is not set. Even after a .Load();
private int HandleEmail(Item item, Folder moveToFolder, Folder moveToFailedFolder, Mailbox mailbox, int fatherId = 0, string uploaderEmail = "", bool isEmbeddedMail = false)
The way it work. is that the HandleEmail() method goes through the original email until it gets the if-check.
If the attachment is not a FileAttachment, and is an ItemAttachment. The following code is called.
else if (attachment is ItemAttachment)
{
var itemAttachment = attachment as ItemAttachment;
itemAttachment.Load(new PropertySet(ItemSchema.Attachments, ItemSchema.TextBody, EmailMessageSchema.Sender, EmailMessageSchema.DisplayCc, EmailMessageSchema.DateTimeReceived, EmailMessageSchema.From, ItemSchema.MimeContent, ItemSchema.Body, ItemSchema.TextBody, EmailMessageSchema.BccRecipients, ItemSchema.Attachments));
var item_ = itemAttachment.Item;
HandleEmail(item_, null, null, mailbox, (int)mailid, uploaderEmail, true); // The attached email is then looped through like it is an regular email instead of like an image.
}
In this check. It takes the item attachment and loads an additional property set, which contains some data that is needed.
Finally the method calls it self, but now with the Item Attachment as to read it like a regular email.
My issue is the fact, that some attached emails do not have the DatetimeReceived property set.
Instead this error is shown in its place.
Microsoft.Exchange.Webservice.Data.ServicesObjectPropertyException
And this expection message is thrown
You must load or assign this property before you can read its value
And I can't quite figure out why it only happens to some attached emails. When I look at the emails it self, it does have an received date. But for some reason I can't get it using .Load()
I've tried a few things, such as using .Load for both Item and ItemAttachment, both without getting anything worthwhile.
Tried looking into using the service.loadpropertiesforitems()
I've forgotten a few of the other things I've looked into, since I have been looking at this for a few days before the weekend aswell.
Two suggestions i would have is first try the EmailMessageSchema.DateTimeSent (which should be the same as DateTimeReceived) the difference maybe being caused when attaching a messages that was sent. The other thing would be enable tracing and have a look at the traces to see what is actually coming back from the server also maybe just try loading the BasePropertySet.FirstClassProperties rather then your custom set (just to test that property anyway)
I'm working with MailKit lib and have a problem.
My application is read specify email in Inbox (Gmail), and delete them.
IList<UniqueId> listUid = inbox.Search(query);
for (int i = 0; i < listUid.Count; i++)
{
var message = inbox.GetMessage(listUid[i]);
inbox.AddFlags(msg.Uid, MessageFlags.Deleted, true);
inbox.Expunge();
}
It run OK, But when Gmail setting Conversation View = Conversation view on, the message that marked as deletion will comback in Inbox if have same email subject and same sender. In next-time I count message, all of deletion message will be re-count. How to avoid it? (save Uid of deletion message is one way but when message number increase, processing will be slow)
Thanks very much.
GMail unfortunately does not behave the same way most other IMAP servers behave and so when you mark a message as \Deleted, it gets moved to the Trash folder automatically and so the Expunge does nothing.
What you need to do is go to your GMail settings and change the behavior of your IMAP account so that it doesn't move the messages to Trash.
Either that or MoveTo() the message to the Trash folder yourself so you can get the UID of the message in the Trash folder (hint: use the return value of the MoveTo() method) and then open the Trash folder and expunge the message from there.
Note: this code is untested, but it should look something like this:
var trash = client.GetFolder (SpecialFolder.Trash);
var moved = client.Inbox.MoveTo (uid, trash);
if (moved.HasValue) {
trash.Open (FolderAccess.ReadWrite);
trash.AddFlags (moved.Value, MessageFlags.Deleted, true);
trash.Expunge (new [] { moved.Value });
}
I'd like a free library for .NET to get attachments from an account (such as gMail, or others) via imap4 (not necessarely), and save them in a folder.
Ideally it would allow me to get a list of them, and download only some given ones (filtering by extension, name, and/or size) and be free.
I've already done this with a trial version of EAGetMail, but for the purpose of what i'm trying to attempt buying the unlimited version of this library isn't quite suitable (i didn't know that this functionality itself was one among the ones with limited time).
---[edit - Higuchi]---
I'm using the following code:
Dim cl As New Pop3Client()
cl.UserName = "marcelo.f.ramires#gmail.com"
cl.Password = "mypassword"
cl.ServerName = "pop.gmail.com"
cl.AuthenticateMode = Pop3AuthenticateMode.Pop
cl.Ssl = False
cl.Authenticate() //takes a while, but passes even if there's a wrong password
Dim mg As Pop3Message = cl.GetMessage(1) //gives me an exception: Message = "Pop3 connection is closed"
UPDATE: Setting the port to 995 gives me a "Response TimeOut" exception
As commented, I am having some issues while trying to connect and get the first e-mail. any help ?
Well, I know you specified IMAP4, but I figured I'd offer this anyway in case POP3 is an option, since it's been useful for me:
http://csharpmail.codeplex.com/
This library provides access to POP3 mail, which many e-mail services (including Gmail) do offer in addition to the newer IMAP.
The core class is Pop3Client, which provides access to POP3 functions such as ExecuteList, ExecuteTop, etc. I have used this for specifically what you are asking about -- scanning for and downloading attachments.
If you decide this is something you could use after all and need further guidance, let me know.
UPDATE: In response to your updated question, I have just a few preliminary suggestions:
Consider setting the Pop3Client.Port property to 995. I know this is what Gmail uses for POP3.
The Pop3Client.Authenticate method returns a bool value indicating whether or not authentication was successful. You can check this value after calling the method to know whether it will be possible to progress further.
UPDATE 2: I tried this at home with the following settings and it worked for me:
Using client As New Pop3Client
client.UserName = "username#gmail.com"
client.Password = "[insert password here]"
client.ServerName = "pop.gmail.com"
client.AuthenticateMode = Pop3AuthenticateMode.Pop
client.Ssl = True ' NOTICE: in your example code you have False here '
client.Port = 995
client.Authenticate()
Dim messageList = client.ExecuteList()
Console.WriteLine("# Messages: {0}", messageList.Count)
End Using
Try these settings and see if they work for you.
UPDATE 3: One more thing! Have you made sure to enable POP for your Gmail account? If not, you need to do that!
From your Gmail inbox, click "Settings" (top right).
From the Settings page, click the tab labeled "Forwarding and POP/IMAP."
In the POP Download section, select one of the radio buttons to enable POP mail.
Click "Save Changes" at the bottom.
The use case is simple. At a certain point of time, I need to be able to show the user his familiar compose email dialog (Outlook or other) with
fields like from, to, Subject already filled up with certain application determined values.
The email would also have an attachment along with it.
The mail should not be sent unless the user explicitly okays it.
I did this once back in the ol' VB6 days.. can't figure out how now.. I just remember that it was quite easy.
Managed app, C#, .net 3.0+
Update#1: Yeah seems like mailto removed support for attachments (as a security risk?). I tried
You need to include ShellExecute signature as described here. All I got from this was a 5 SE_ERR_ACCESSDENIED and a 2 just for some variety
string sMailToLink = #"mailto:some.address#gmail.com?subject=Hey&body= yeah yeah yeah";
IntPtr result = ShellExecute(IntPtr.Zero, "open", sMailToLink, "", "", ShowCommands.SW_SHOWNORMAL);
Debug.Assert(result.ToInt32() > 32, "Shell Execute failed with return code " + result.ToInt32());
The same MailtoLink works perfectly with Process.Start... but as long as thou shalt not mention attachments.
System.Diagnostics.Process.Start(sMailToLink);
The other options are using the Outlook Object model to do this.. but I've been told that this requires you to add assembly references based to the exact version of Outlook installed. Also this would blow up if the user doesn't prefer MS for email.
The next option are Mapi and something called Mapi33.. Status still IN PROGRESS. Ears still open to suggestions.
You can create a process object and have it call "mailto:user#example.com?subject=My+New+Subject". This will cause the system to act on the mailto with its default handler, however, while you can set subjects and such this wont handle adding an attachment. I'll freely admit im not entirely sure how you'd go about forcing an attachment without writing some mail plugin.
The process code is:
System.Diagnostics.Process.Start("mailto:user#example.com?subject=My+New+Subject");
It's probably not the most efficient or elegant way, but shelling a "mailto:" link will do what you want, I think.
EDIT: Sorry, left out a very important "not".
Since mailto does not support attachments, and since MAPI is not supported within managed code, your best bet is to write (or have someone write) a small non-managed program to call MAPI functions that you can call with command-line arguments. Pity that .NET does not have a cleaner alternative.
See also : MAPI and managed code experiences?
Could it be that you used the mailto: protocol?
Almost all of what you highlight can be done, but I am quite sure, that you cant do attachments.
Microsoft MailTo Documentation
Starting process with mailto: arguments is the simplest approach. Yet, it does not allow anything more or less complex.
Slightly different approach involves creating email template and then feeding it to the Process.Start:
var client = new SmtpClient();
var folder = new RandomTempFolder();
client.DeliveryMethod =
SmtpDeliveryMethod.SpecifiedPickupDirectory;
client.PickupDirectoryLocation = folder.FullName;
var message = new MailMessage("to#no.net",
"from#no.net", "Subject","Hi and bye");
// add attachments here, if needed
// need this to open email in Edit mode in OE
message.Headers.Add("X-Unsent", "1");
client.Send(message);
var files = folder.GetFiles();
Process.Start(files[0].FullName);
Scenarios for the default email handler:
Outlook express opens
Windows: Outlook - does not handle by default, Outlook Express is called instead
Windows: The Bat! - message is opened for viewing, hit Shift-F6 and Enter to send
I've also tested with Mono and it worked more or less.
Additional details are available in this post: Information integration - simplest approach for templated emails
PS: in the end I went for slightly more complex scenario:
Defined interface IEmailIntegraton
Code above went into the DefaultEmailIntegration
Added implementations for OutlookEmailIntegration (automation) and theBat! email integration (using their template format).
Allowed users of the SmartClient to select their scenario from the drop-down (alternatively this could've been implemented as "Check the system for the default email handler and decide automatically")
You're making the assumption that they will have an email client installed, of course.
The option I've taken in the past (in a corporate environment where everyone has at least one version of Outlook installed) was to use the Outlook interop - you only need to reference the earliest version you need to support.
You could look at P/Invoking MAPISendDocuments (which I'd try and avoid, personally), or the other option would be to create your own "compose" form and use the objects from the System.Net.Mail namespace.
you can use a trick if you intend to use Outlook[this code is based on outlook 2010[v14.0.0.]]
Create Outlook MailItem
and transmit file (ie download)
if user opens the file (.msg) the compose message dialog opens automatically
here is the code ...
Microsoft.Office.Interop.Outlook.Application outapp = new Application();
try
{
_NameSpace np = outapp.GetNamespace("MAPI");
MailItem oMsg = (MailItem)outapp.CreateItem(OlItemType.olMailItem);
oMsg.To = "a#b.com";
oMsg.Subject = "Subject";
//add detail
oMsg.SaveAs("C:\\Doc.msg", OlSaveAsType.olMSGUnicode);//your path
oMsg.Close(OlInspectorClose.olSave);
}
catch (System.Exception e)
{
status = false;
}
finally
{
outapp.Quit();
}
then transmit the file you created say "Doc.msg"
string filename ="Doc.msg";//file name created previously
path = "C:\\" + filename; //full path ;
Response.ContentType="application/outlook";
Response.AppendHeader("Content-Disposition", "filename=\"" + filename + "\"");
FileInfo fl = new FileInfo(path);
Response.AddHeader("Content-Length", fl.Length.ToString());
Response.TransmitFile(path,0,fl.Length);
Response.End();