How to mark unseen last unread message S22.imap - c#

How read last unread message from mail box and after mark this message "Unseen"
I use s22.imap.dll
ImapClient Client = new ImapClient("imap.gmail.com", 993, "My_Username",
"My_Password", true, AuthMethod.Login);
// Get a list of unique identifiers (UIDs) of all unread messages in the mailbox.
uint[] uids = Client.Search( SearchCondition.Unseen() );
// Fetch the messages and print out their subject lines.
foreach(uint uid in uids) {
MailMessage message = Client.GetMessage(uid);
Console.WriteLine(message.Subject);
}
// Free up any resources associated with this instance.
Client.Dispose();

First get uid last unread message:
var lastUid = Client.Search( SearchCondition.Unseen().Last() );
and read this message;
MailMessage message = Client.GetMessage( lastUid );
To mark this message as "Unseen":
Client.RemoveMessageFlags( lastUid, null, MessageFlag.Seen );
See more on: ImapClient.RemoveMessageFlags Method

Related

C# Exchange EmailMessage Send: As soon as I add an attachement, I get error "No mailbox with such guid"

In my application I use some code to send automated mails over our Exchange server.
My current goal is to send a HTML mail with some pictures as a handout. That pictures shall be attachments of the mail.
To this point the code is working (I have changes internal names in the code example):
ExchangeService MailClient = new ExchangeService
{
UseDefaultCredentials = true,
Url = new Uri("https://<domain.of.company>/EWS/Exchange.asmx")
};
EmailMessage msg = new EmailMessage(MailClient);
msg.ToRecipients.Add(new EmailAddress(user.EmailAddress));
msg.Sender = new EmailAddress("sender#domain.of.company");
msg.Subject = "Some text here";
MessageBody Body = new MessageBody
{
BodyType = BodyType.HTML,
Text = NameOfApplication.Properties.Resources.Embedded_HTML_File
};
msg.Body = Body;
msg.SendAndSaveCopy(new FolderId(WellKnownFolderName.SentItems, "sender#domain.of.company")));
With this code the E-Mail get saved in the "Sent" folder and arrives the target mailbox. Success so far.
But as soon I add an attachement by this (no other changes were made)
msg.Attachments.AddFileAttachment(AppContext.BaseDirectory + "Logo.jpg");
SendAndSaveCopy throws an exception with the description "No mailbox with such guid."
When I comment out the AddFileAttachment line the code is working again.
Any idea whats wrong with attachments?
Found the solution. Reading tooltips might help.
Maybe the day will come, when Microsoft will change SendAndSaveCopy to include this step.
But yes: The error message is misleading.

Send Reply with attachment using Microsoft Graph API

I've been working with Microsoft graph API to receive and reply to the mail.
I've successfully received and send mails, but as per Graph API docs in reply only a comment can be passed.
https://learn.microsoft.com/en-us/graph/api/message-createreply?view=graph-rest-1.0&tabs=cs
I've developed the send mail code as shown below:-
IList<Recipient> messageToList = new List<Recipient>();
User currentUser = client.Me.Request().GetAsync().Result;
Recipient currentUserRecipient = new Recipient();
EmailAddress currentUserEmailAdress = new EmailAddress();
EmailAddress recepientUserEmailAdress = new EmailAddress();
currentUserEmailAdress.Address = currentUser.UserPrincipalName;
currentUserEmailAdress.Name = currentUser.DisplayName;
messageToList.Add(currentUserRecipient);
try
{
ItemBody messageBody = new ItemBody();
messageBody.Content = "A sample message from Ashish";
messageBody.ContentType = BodyType.Text;
Message newMessage = new Message();
newMessage.Subject = "\nSample Mail From Ashish.";
newMessage.ToRecipients = messageToList;
newMessage.CcRecipients = new List<Recipient>()
{
new Recipient
{
EmailAddress = new EmailAddress
{
Address = "abc.xyz#xxxx.com"
}
}
};
newMessage.Body = messageBody;
client.Me.SendMail(newMessage, true).Request().PostAsync();
Console.WriteLine("\nMail sent to {0}", currentUser.DisplayName);
}
catch (Exception)
{
Console.WriteLine("\nUnexpected Error attempting to send an email");
throw;
}
This code is working fine!!
Can someone please share how I can Reply to a mail with attachment and mailbody like I'm able to do in Send mail.
Thanks in advance.
You have to create a reply, add the attachment, and then send the message. With the basic basic /reply endpoint you cant do it.
E.g.:
Create the message draft using POST request
As a response you will get the whole message structure with id set to something like AQMkADAwATMwMAItMTJkYi03YjFjLTAwAi0wMAoARgAAA_hRKmxc6QpJks9QJkO5R50HAP6mz4np5UJHkvaxWZjGproAAAIBDwAAAP6mz4np5UJHkvaxWZjGproAAAAUZT2jAAAA. Lets refer to it as {messageID}.
After that you can create an attachment using POST request to https://graph.microsoft.com/beta/me/messages/{messageID}/attachments
-After step 2 you will see created message in your mailbox Drafts folder. To send it use https://graph.microsoft.com/beta/me/messages/{messageID}/send
Hope it helps.

How to set mail as 'Important' of gmail using google apis in c#?

I am trying to add mail in gmail account using google apis in c#.
Message f_msg = new Message();
f_ReqforMail = m_MailService.Users.Messages.Insert(f_msg, "me");
How to set that f_msg mail object as 'Important'?
Thanks.
You can try to set the MailPriority Enumeration as:
f_msg.Priority = MailPriority.High
Specifies the priority of a MailMessage.
Remarks
You can use this enumeration to set the priority header of an email
message.
If you are using AE.Net.Mail to Build your MailMessage Then You can Use AE.Net.Mail.MailPriority.High to set the Priority. Here is an example:
MailMessage msg = new AE.Net.Mail.MailMessage
{
Subject = "Your Subject",
Body = "Hello, World, from Gmail API!",
From = new MailAddress("[you]#gmail.com"),
Importance=AE.Net.Mail.MailPriority.High
};
I use:
AE.Net.Mail.MailMessage message = client.GetMessage(uid);
bool isHighLight = message.RawFlags.ToList().Contains("Flagged") ? true : false;

How to decide Bounce Back EmailMessage on Office365?

I'm using Exchange web service to read email from Office365. The C# program works fine. I can get EmailMessage in Inbox, and get their subject and message body, etc. However, I could not figure out the way to check whether the message is a bounce back message or not.
Do I have to parse the message body to see whether there are some special sentence, ie. Mail Delivery Failure? If so, is it possible different email servers bounce back emails with different words? i.e some use 'Mail Delivery Failure', some use 'Mail Delivery Not Succeeded'? (just an example, I do not know whether this is true)
Or, the message object has an attribute that can be used for this purpose?
Thanks
*** Just found that the exchange webservice can not see 'Bounce back' messages in INBOX. I'm using below code, all messages can be 'seen' except Bounce Back ones. Do I miss anything to filter te bounce back messages? They are actually in INBOX, unread, and I can see it from Office365 page.
private static void ProcessEmailMessages(SearchFolder searchFolder, Folder folderHistory, Folder folderBounceBack)
{
if (searchFolder == null)
{
return;
}
const Int32 pageSize = 50;
ItemView itemView = new ItemView(pageSize);
PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties);
itempropertyset.RequestedBodyType = BodyType.Text;
itemView.PropertySet = itempropertyset;
PropertySet propertySet = new PropertySet(BasePropertySet.IdOnly, FolderSchema.DisplayName);
folderHistory.Load(propertySet);
folderBounceBack.Load(propertySet);
FindItemsResults<Item> findResults = null;
do
{
findResults = searchFolder.FindItems(itemView);
foreach (Item item in findResults.Items)
{
if (item is EmailMessage)
{
// load body text
item.Load(itempropertyset);
EmailMessage email = item as EmailMessage;
//email.Move(folder.Id);
// check email subject to find the bounced emails
bool subjectContains = Regex.IsMatch(email.Subject, "Mail Delivery Failure", RegexOptions.IgnoreCase);
bool bodyContains = Regex.IsMatch(email.Subject, "Delivery", RegexOptions.IgnoreCase);
if (subjectContains || bodyContains)
{
email.Move(folderBounceBack.Id);
Console.WriteLine("Move the Bounced email: {0}", email.Subject);
ShowMessageInfo(email);
}
else
{
email.Move(folderHistory.Id);
Console.WriteLine(">>> Keep the email: {0}", email.Subject);
}
}
}
itemView.Offset += pageSize;
} while (findResults.MoreAvailable);
}
Check the ItemClass attribute. Messages like that should have a class that contains "REPORT" in it.
I use EWS in an O365 environment to help process bounce backs and use the following code to just get the NDRs from a users' inbox.
var sf = new SearchFilter.IsEqualTo(ItemSchema.ItemClass, "REPORT.IPM.Note.NDR");
var SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, sf);
var view = new ItemView(1000) {PropertySet = new PropertySet(BasePropertySet.IdOnly)};
var findResults = service.FindItems(WellKnownFolderName.Inbox, searchFilter, view);
Hope it helps.

How to get receiver email from a sent email in EWS?

I'm looping sent item in EWS, and try to show details of each sent emails, receiver, subject, body etc. However, I found receiver in the sent email message is null. How to get receiver email address?
My code:
ItemId id = (ItemId)Request["id"]; // this id is the item id of WellKnownFolderName.**SentItems**
EmailMessage current = EmailMessage.Bind(service, id);
La_Subject.Text = current.Subject;
La_From.Text = current.Sender.ToString();
La_Sent.Text = current.DateTimeReceived.ToString();
La_To.Text = current.ReceivedBy.ToString(); // This line error occurs
Any idea?
To get the recipients of a mail, use the DisplayTo and DisplayCC properties of the mail message.
Or iterate through the ToRecipients collection yourself and build the string yourself:
var toRecipients = string.Join(", ",
mail.ToRecipients.Select(
address => string.Format("\"{0}\" <{1}", address.Name, address.Address)));
The ReceivedBy property is used in delegate scenarios. See http://msdn.microsoft.com/en-us/library/microsoft.exchange.webservices.data.emailmessage.receivedby(v=exchg.80).aspx.

Categories

Resources