How to get mail sent successfully with MailKit IMap? - c#

I'd like to know if my outbox mail has been sent successfully..
var client = new ImapClient();
....
var folders = client.GetFolders(client.PersonalNamespaces[0]);
var folder = client.GetFolder("已发送");//get sent mail floder in Chinese
var folderAccess = folder.Open(FolderAccess.ReadOnly);
string path = #"C:\temp\";
for (int i = folder.Count - 1; i >= 0; i--)
{
var message = folder.GetMessage(i);
}

You can't send messages via IMAP, you can only send them via SMTP.
Sending messages via SMTP do not put them into any IMAP folder. You have to put them there yourself.

Related

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.

Mail Sending to multiple users in Dynamics CRM + Plugin

I'm writing plugin C#, to send an email to the users who are under SystemCustomizer role notifying that Contact is creating or Updating.
How to send an email to multiple users (Bulkmailing/ forEach loop for creating mail request to every user)?
Use a query to find each system user entity with the system customiser role.
Then for each user send an email. 1; create the email, 2; send the email.
// Create an e-mail message.
Email email = new Email
{
To = new ActivityParty[] { toParty },
From = new ActivityParty[] { fromParty },
Subject = "SDK Sample e-mail",
Description = "SDK Sample for SendEmail Message.",
DirectionCode = true
};
_emailId = _serviceProxy.Create(email);
// Use the SendEmail message to send an e-mail message.
SendEmailRequest sendEmailreq = new SendEmailRequest
{
EmailId = _emailId,
TrackingToken = "",
IssueSend = true
};
SendEmailResponse sendEmailresp = (SendEmailResponse)_serviceProxy.Execute(sendEmailreq);

MailKit.Net.Imap read Gmail attachments when "Content-Disposition; inline" is set

I have a c# console application that I use to search a Gmail account for emails with attachments and download them. I am using MailKit.Net.Imap.ImapClient to do this.
If the email has been sent with the "Content-Disposition; attachment" set then all works well. If the email has been sent with "Content-Disposition; inline" set, the ImapClient does not see the attachments and I can't download them.
Below is the code I use to do this. Does anyone have any idea how to fix this?
static public void mail_ReadEmail()
{
string mail_login = "your login here";
string mail_password = "your password here";
string mail_folderName = "your gmail folder name here";
// Get client & open folder
ImapClient client = mail_GetImapClient(mail_login, mail_password);
IMailFolder folder = mail_GetIMailFolder(client, mail_folderName);
// Get emails
DateTime startTime = DateTime.Now.AddMonths(-6);
IList<UniqueId> email = folder.Search(SearchQuery
.DeliveredAfter(startTime)
.And(SearchQuery
.FromContains("canon.co.nz")));
// Loop through emails (oldest first)
for (int i = email.Count - 1; i >= 0; i--)
{
// Get message and display subject and date
MimeMessage message = folder.GetMessage(email[i]);
Console.WriteLine(message.Subject + " - " + message.Date.DateTime.ToShortDateString());
// Show all attachments for this message
foreach (MimePart part in message.Attachments)
Console.WriteLine("\t* " + part.FileName);
}
}
You can use the BodyParts property instead of the Attachments property.
For example, you could do this:
foreach (MimePart part in message.BodyParts.OfType<MimePart> ().Where (x => x.IsAttachment || (/* other criteria that suggests an attachment */))
Console.WriteLine("\t* " + part.FileName);
If you want to treat all MimeParts with a Content-Disposition filename attribute or a Content-Type name attribute set, then you could do:
!string.IsNullOrEmpty (x.FileName)

MailKit delete Emails Xamarin C#

I am using mailkit on monotouch xamarin. I am creating an app that will receive emails(email client). I give to the user the option to choose if he is using Pop3 or IMAP connection protocol. My issue is that I cant find solution on how he can delete a message on Pop3 and on IMAP.
I have tried to use this code:
client.Inbox.AddFlags (new int[] { index }, MessageFlags.Deleted);
from this post: MailKit Delete single message from gmail
but is not seems to work for me.
My code for capturing the Pop3 acount emails is
using (var client = new Pop3Client ()) {
var credentials = new NetworkCredential (Convert.ToString (username), Convert.ToString (password));
var uri = new Uri (Convert.ToString ("pops://"+pop3));
using (var cancel = new CancellationTokenSource ()) {
client.Connect (uri, cancel.Token);
var _emailItems=new List<EmailItem>() ;
client.Authenticate (credentials, cancel.Token);
string[] mycell = new string[200];
int count = client.GetMessageCount (cancel.Token);
int lastcount;
for (int i = 0; i < count; i++) {
lastcount = (count - 1) - i;
var message = client.GetMessage (lastcount, cancel.Token);
}
}
}
Different protocols have different ways of deleting messages.
For POP3, this is how you would delete a message:
client.DeleteMessage (lastcount, cancel.Token);
(Note: unless you are actually allowing the user to cancel the operations, you do not need to use cancel.Token)
The other way of deleting messages that you pasted is meant for IMAP.

Exchange web services - Forward Email as Attachment

I'm currently using Exchange Web Services in C#. I basically have a small application that reads emails from an inbox and process them.
I would like to forward those emails I receive as an attachment of an email. This attachment will be an outlook email that will include the original email (including its own attachments if any).
Any ideas?
Thanks!
EDIT:
Not sure why I'm getting the down votes but it seems this is not possible as the EWS API does not provide such functionality
You can create an ItemAttachment with EWS but you can't replicate fully what is possible in Outlook with MAPI. Eg with EWS you can create an ItemAttachment and then use the MIMEContent to create an attachment based on a current message as a workaround eg
FolderId Inboxid = new FolderId(WellKnownFolderName.Inbox, "target#domain.com");
ItemView InboxItemView = new ItemView(1);
FindItemsResults<Item> inFiResuls = service.FindItems(Inboxid,InboxItemView);
if(inFiResuls.Items.Count == 1){
EmailMessage fwdMail = new EmailMessage(service);
EmailMessage orgMail = (EmailMessage)inFiResuls.Items[0];
PropertySet psPropSet = new PropertySet(BasePropertySet.FirstClassProperties);
psPropSet.Add(ItemSchema.MimeContent);
orgMail.Load(psPropSet);
ItemAttachment emAttach = fwdMail.Attachments.AddItemAttachment<EmailMessage>();
emAttach.Item.MimeContent = orgMail.MimeContent;
ExtendedPropertyDefinition pr_flags = new ExtendedPropertyDefinition(3591,MapiPropertyType.Integer);
emAttach.Item.SetExtendedProperty(pr_flags,"1");
emAttach.Name = orgMail.Subject;
fwdMail.Subject = "see Attached";
fwdMail.ToRecipients.Add("user#domain.com");
fwdMail.Send();
}
This however doesn't give full fidelity of all the mapi properties associated with a particular message as the MIMEContent is just that, for most normal email messages this isn't an issue however for a message with an attached Outlook Task or other TNEF attachment then you would loose these of attachments or for other properties like categories,flags you would loose these also (you could copy these manually if needed).
Cheers
Glen
you can forward your email using this way. It first loads and reads the each emails with attachment who has "msg" extension. then forwards it to given address. see the below code
FindItemsResults<Item> findResults = exchange.FindItems(WellKnownFolderName.Inbox, newItemView(50,50));
Item[] msgItems = findResults.Where(msgItem => msgItem.HasAttachments).ToArray();
EmailMessage msgInfo = null;
var fileExtensions = new List<string> { "msg", "MSG", "Msg" };
foreach (MSEWS.Item msgItem in msgItems )
{
msgInfo = EmailMessage.Bind(exchange, msgItem.Id);
FileAttachment fa = msgInfo.Attachments[0] asFileAttachment;
if (fileExtensions.Any(ext => ext.Contains(fa.Name.Substring(fa.Name.Length - 3))))
{
fa.Load();
ResponseMessage responseMessage = msgInfo.CreateForward();
responseMessage.BodyPrefix = "messageBody";
responseMessage.ToRecipients.Add("toAddress");
responseMessage.Subject = "subject";
responseMessage.SendAndSaveCopy();
}
}

Categories

Resources