Simple Authentication Security Layer: This is for the authentication methods that require OAUTH2 or other methods.
//Direct creationvar saslDirect =newSaslMechanismOAuth2("","");//If using GMAIL, we built in the google auth flowvar googleSASL =MailWatcher.SASL_GoogleAPIS("email","CredentialPath.json");
The BodyBuildercallback is how you configure the outgoing message. You can see an example here of adding an image with CIDs.
The Reply method automatically configures the method reply parameters including the correct message headers, subject, response addresses, and if includeReplyText is true, it will also quote the original message back as any normal client would do.
//Generate a reply with the correct message contentsvar mReply =mail.Reply(false, (bb) => { //Set HTML, and text fallback contentbb.TextBody="text is supported";bb.HtmlBody="<b>html</b> is supported"; //Add an attachment //bb.Attachments.Add("MyPDF", File.ReadAllBytes("MyPDF.pdf")); }, includeReplyText:true); //Sendmail.SendMessage(mReply);
To delete a message, issue the delete command.
The parameter is for expunging the message from the server as well as issuing the deleted flag.
mail.DeleteMail(true);
Attachments
You can get a list of attachment parts, and iterate over them to get the actual content, mime type, name, etc.
//This does not pull the body or content, and is a fast way of checking how many attachments a message hasvar attachcount =mail.Message.Attachments.Count();//This iterates over the bodyparts to get additional information, it is slower and should be used after there are known messagesvar attachments =mail.GetAttachments();if (attachments.Any()){var attach =attachments.ElementAt(0);var name =attach.FileName;usingMemoryStream attachBytes =mail.GetAttachment(attach);}
Querying
To query the inbox:
var uidsNotAnswered =mail.GetNotAnsweredUIDs();if (uidsNotAnswered.Any()){var ListMailSummaries =mail.FetchMessages(uidsNotAnswered);}var uidsNotSeen =mail.GetNotSeenUIDs();if (uidsNotSeen.Any()){var ListMailSummaries =mail.FetchMessages(uidsNotSeen);}//Or direct access querying:var uids =mail.Folder.Search(MailKit.Search.SearchQuery.DeliveredAfter(DateTime.UtcNow.AddDays(-1)));
Sent Box
If you need to access the sent box, we provide an easy way to retrieve and open the sent mailbox.
var sentBox =mail.GetAndOpenSentFolder();if (sentBox !=null){var uids =sentBox.Search(MailKit.Search.SearchQuery.DeliveredAfter(DateTime.UtcNow.AddDays(-1))); //Fetch using the sentbox, as mail.FetchMessages uses the inbox.var ListMailSummaries =sentBox.FetchAsync(uids,mail.MessagePullItems).GetAwaiter().GetResult(); //make sure you're "using MailKit;"}
IMAP only allows a single mailbox to be open at once. Don't forget to call:
mail.OpenInbox();.
This verifies and prevents future issues with any subsequent calls to the mail client.
Input Text
Sometimes you just need whatever the person said, excluding their signature and reply content. This method takes several passes at retrieving just the top level user input and skipping the rest:
string textOnlyPart =mail.GetOnlyInputTextBody();
Low Level Access
There are a bunch of prebuilt methods to help with a mail client. If you want to do something specific, you can get the client and folder access as so, and use any of the available methods from MailKit:
var imapClient =mail.Client;var imapInbox =mail.Folder;
Best practice watching
We highly recommend:
Putting a stop gap on the mail receive handler, something like IsAnswered, as a way of preventing unwanted reprocessing of messages.
Catching the exception and attempting to mark it answered and label it error if the client supports labelling.
PerigeeApplication.ApplicationNoInit("MailDemo", (c) => {c.AddIMAPWatcher("MailWatch","email@address.com","MailBot","hostImap",993,"smtphost",587, () =>MailWatcher.SASL_GoogleAPIS("email@address.com","CredentialPath.json"), (ct, l, mail) => {try {if (!mail.IsAnswered) { //Do stuff here! //Mark it on successmail.AddFlags(MessageFlags.Answered|MailKit.MessageFlags.Seen);mail.AddLabels("success"); } }catch (Exception ex) {l.LogError(ex,"Uncaught exception in mail processor");try {mail.AddFlags(MessageFlags.Answered|MailKit.MessageFlags.Seen);mail.AddLabels("error"); }catch (Exception) { } } });});