I have a mail containing only a signature as an image and an attachment like the screenshot below.
I save this email as C:\mail.msg, I try then to read it by the code below:
var oApp = new Microsoft.Office.Interop.Outlook.Application();
MailItem outlookMsg = (Microsoft.Office.Interop.Outlook.MailItem)oApp.CreateItemFromTemplate(#"C:\mail.msg");
//there are 2 attachments inside
foreach(var att in outlookMsg.Attachments)
{
att.SaveAsFile($#"C:\{att.FileName}");
}
The problem
There are 2 attachments inside the MailItem named :
-empty.xlsx
-lot4.xlsx
If I change the extension of lot4.xlsx to lot4.png, it can be opened as the image in the signature.
Someone has seen this strange situation when an attachment is added with name incorrect?
You could download attachments using the below code:
private void ThisApplication_NewMail()
{
Outlook.MAPIFolder inBox = this.Application.ActiveExplorer()
.Session.GetDefaultFolder(Outlook
.OlDefaultFolders.olFolderInbox);
Outlook.Items inBoxItems = inBox.Items;
Outlook.MailItem newEmail = null;
inBoxItems = inBoxItems.Restrict("[Unread] = true");
try
{
foreach (object collectionItem in inBoxItems)
{
newEmail = collectionItem as Outlook.MailItem;
if (newEmail != null)
{
if (newEmail.Attachments.Count > 0)
{
for (int i = 1; i <= newEmail
.Attachments.Count; i++)
{
newEmail.Attachments[i].SaveAsFile
(#"C:\TestFileSave\" +
newEmail.Attachments[i].FileName);
}
}
}
}
}
catch (Exception ex)
{
string errorInfo = (string)ex.Message
.Substring(0, 11);
if (errorInfo == "Cannot save")
{
MessageBox.Show(#"Create Folder C:\TestFileSave");
}
}
}
For more information, please refer to this link:
How to: Programmatically save attachments from Outlook email items
With Microsoft EWS, its very easy to do:
reference: http://johnlabtest.blogspot.com/2014/01/save-attachments-from-exchange-mail-box.html
static void Main(string[] args)
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
service.Credentials = new WebCredentials("user1#contoso.com", "password");
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
service.AutodiscoverUrl("user1#contoso.com", RedirectionUrlValidationCallback);
var messages = new List<EmailMessage>();
// only get unread emails
SearchFilter folderSearchFilter = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false);
// we just need the id in our results
var itemView = new ItemView(10) {PropertySet = new PropertySet(BasePropertySet.IdOnly)};
FindItemsResults<Item> findResults = service.FindItems(folder.Id, folderSearchFilter, itemView);
foreach (Item item in findResults.Items.Where(i => i is EmailMessage))
{
EmailMessage message = EmailMessage.Bind(service, item.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments, ItemSchema.HasAttachments));
messages.Add(message);
}
// loop through messages and call processemail here.
}
public static void ProcessEmail(EmailMessage message)
{
string saveDir = ConfigurationManager.AppSettings["AttachmentSaveDirectory"];
if (message.HasAttachments)
{
foreach (Attachment attachment in message.Attachments.Where(a=> a is FileAttachment))
{
FileAttachment fileAttachment = attachment as FileAttachment;
fileAttachment.Load(); // populate the content property of the attachment
using (FileStream fs = new FileStream(saveDir + attachment.Name, FileMode.Create))
{
using (BinaryWriter w = new BinaryWriter(fs))
{
w.Write(fileAttachment.Content);
}
}
}
}
message.IsRead = true;
message.Update(ConflictResolutionMode.AutoResolve); // push changes back to server
}
private static bool RedirectionUrlValidationCallback(string redirectionUrl)
{
// The default for the validation callback is to reject the URL.
bool result = false;
Uri redirectionUri = new Uri(redirectionUrl);
// Validate the contents of the redirection URL. In this simple validation
// callback, the redirection URL is considered valid if it is using HTTPS
// to encrypt the authentication credentials.
if (redirectionUri.Scheme == "https")
{
result = true;
}
return result;
}
Related
If we have the UniqueId to the mail we wish to move the attachment to via the usage of an ImapClient, how exactly can we achieve this?
Thank you!
UniqueId? AddAttachmentToMessage (ImapClient client, ImapFolder folder, UniqueId uid, MimeEntity attachment)
{
var message = folder.GetMessage (uid);
var body = message.Body;
Multipart multipart;
if (message.Body is Multipart && message.Body.ContentType.IsMimeType ("multipart", "mixed")) {
multipart = (Multipart) message.Body;
} else {
multipart = new Multipart ("mixed");
multipart.Add (message.Body);
message.Body = multipart;
}
multipart.Add (attachment);
var newUid = folder.Append (message);
folder.AddFlags (uid, MessageFlags.Deleted, true);
if (client.Capabilities.HasFlag (ImapCapabilities.UidPlus))
folder.Expunge (new UniqueId[] { uid });
return newUid;
}
If the server doesn't support UIDPLUS and you need the newUid value, then you can probably do something like this:
if (!client.Capabilities.HasFlag (ImapCapabilities.UidPlus)) {
var initialUids = folder.Search (SearchQuery.All);
folder.Append (message);
var updatedUids = folder.Search (SearchQuery.All);
// find the new uids
var newUids = new UniqueIdSet (SortOrder.Ascending);
for (int i = updatedUids.Count - 1; i >= 0; i--) {
if (!initialUids.Contains (updatedUids[i]))
newUids.Add (updatedUids[i]);
}
// get envelope info for each of the new messages
var newItems = folder.Fetch (newUids, MessageSummaryItems.UniqueId | MessageSummaryItems.Envelope);
foreach (var item in newItems) {
var msgid = MimeUtils.ParseMessageId (item.Envelope.MessageId);
if (message.MessageId.Equals (msgid))
return item.UniuqeId;
// Note: if you want to be more pedantic, you can compare the From/To/Cc/ReplyTo and Subject fields as well.
}
}
After sending an email the logo is not displayed in Outlook but it works in Gmail.
I found that in the inspect element that the image src is changed into blockedimagesrc
In my Controller :
var NotifyCompany = new NotifyCompany()
{
Email = model.regE,
EmailTo = contact.GetPropertyValue<string>("email"),
DateRegistered = DateTime.UtcNow
};
EmailHelpers.SendEmail(NotifyCompany, "NotifyCompany", "New Client Registered");
Helpers :
public static ActionResponse SendEmail(IEmail model, string emailTemplate, string subject, List<HttpPostedFileBase> files = null)
{
try
{
var template =
System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath(string.Format("~/Templates/{0}.cshtml", emailTemplate)));
var body = Razor.Parse(template, model);
var attachments = new List<Attachment>();
if (files != null && files.Any())
{
foreach (var file in files)
{
var att = new Attachment(file.InputStream, file.FileName);
attachments.Add(att);
}
}
var email = Email
.From(ConfigurationManager.AppSettings["Email:From"], "myWebsiteEmail")
.To(model.EmailTo)
.Subject(subject)
.Attach(attachments)
.Body(body).BodyAsHtml();
email.Send();
return new ActionResponse()
{
Success = true
};
}
catch (Exception ex)
{
return new ActionResponse()
{
Success = false,
ErrorMessage = ex.Message
};
}
}
In my Email Template :
<img src="/mysite.com/image/logo.png"/>
Any help would be appreciated.
Outlook web access will block any images by default - only if the user chooses to display/download images these will be displayed/downloaded. I am not sure if it is possible to adjust the default behavior by using office 365 admincenter or the OWA settings.
Some time ago it was possible to work around this by using it as a background image inside a table>tr>td cell background-image css property.
EDIT
Checked a recent project of myself, where we are sending notification mails about tickets. The site logo is displayed correctly in outlook/owa - without adding the recipient to the trusted list:
using (MailMessage mm = new MailMessage(sender, header.RecipientAddress, header.Subject, header.Body))
{
mm.Body = header.Body;
mm.BodyEncoding = Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
mm.Priority = priority == IntMailPriority.High ? MailPriority.High : MailPriority.Normal;
mm.IsBodyHtml = bodyIsHtml;
// logo
if (bodyIsHtml)
{
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(header.Body, Encoding.UTF8, "text/html");
string logoPath = $"{AppDomain.CurrentDomain.BaseDirectory}\\images\\logo_XXX.png";
LinkedResource siteLogo = new LinkedResource(logoPath)
{
ContentId = "logoId"
};
htmlView.LinkedResources.Add(siteLogo);
mm.AlternateViews.Add(htmlView);
}
// create smtpclient
SmtpClient smtpClient = new SmtpClient(smtpSettings.ServerAddress, smtpSettings.Port)
{
Timeout = 30000,
DeliveryMethod = SmtpDeliveryMethod.Network
};
// set relevant smtpclient settings
if (smtpSettings.UseTlsSsl)
{
smtpClient.EnableSsl = true;
// needed for invalid certificates
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
}
if (smtpSettings.UseAuth)
{
smtpClient.UseDefaultCredentials = false;
NetworkCredential smtpAuth = new NetworkCredential { UserName = smtpSettings.Username, Password = smtpSettings.Password };
smtpClient.Credentials = smtpAuth;
}
smtpClient.Timeout = smtpSettings.SendingTimeout * 1000;
// finally sent mail \o/ :)
try
{
smtpClient.Send(mm);
}
catch (SmtpException exc)
{
throw new ProgramException(exc, exc.Message);
}
catch (InvalidOperationException exc)
{
throw new ProgramException(exc, exc.Message);
}
catch (AuthenticationException exc)
{
throw new ProgramException(exc, exc.Message);
}
}
Afterwards the logo is referred to as
<IMG alt="Intex Logo" src="cid:logoId">
inside the generated html.
Referring to the answer mentioned in the post:
Reading Outlook Mail with C#
This code works well for a single account, but the issue with the current code is that it reads the email of the default id which was set as the first one in the outlook app.
For example, if "abcxyz#outlook.com" is set as the first account and "decxyz#outlook.com" is set as the second one, then it reads the inbox of only the first id, i.e., "abcxyz#outlook.com". I tried doing some modifications in the code but it did not work. Below is my code:
public static void OutLookMailStart(string EmailID, string password)
{
Microsoft.Office.Interop.Outlook.Application app = null;
Microsoft.Office.Interop.Outlook._NameSpace ns = null;
Microsoft.Office.Interop.Outlook.PostItem item = null;
Microsoft.Office.Interop.Outlook.MAPIFolder inboxFolder = null;
Microsoft.Office.Interop.Outlook.MAPIFolder subFolder = null;
Microsoft.Office.Interop.Outlook.MailItem mailItem = null;
try
{
app = new Microsoft.Office.Interop.Outlook.Application();
ns = app.GetNamespace("MAPI");
ns.Logon(EmailID, password, false, true);
inboxFolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
foreach (Object mail in inboxFolder.Items)
{
if ((mail as MailItem) != null && (mail as MailItem).UnRead == true)
{
// Email Subject
string Subject = (mail as MailItem).Subject.ToString();
if (Subject.Contains(FileDomain))
{
// Email Body
var ReplyText = ExtractReply(((mail as MailItem).Body.ToString()), FromTrimName);
}
// (mail as MailItem).UnRead = false;
(mail as MailItem).Save();
}
}
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
ns.Logoff();
inboxFolder = null;
subFolder = null;
mailItem = null;
app = null;
}}
Any sort of help will be appreciated.
public static void OutLookMailStart(string EmailID, string password)
{
Microsoft.Office.Interop.Outlook.Application app = null;
Microsoft.Office.Interop.Outlook._NameSpace ns = null;
Microsoft.Office.Interop.Outlook.PostItem item = null;
Microsoft.Office.Interop.Outlook.MAPIFolder inboxFolder = null;
Microsoft.Office.Interop.Outlook.MAPIFolder subFolder = null;
Microsoft.Office.Interop.Outlook.MailItem mailItem = null;
try
{
app = new Microsoft.Office.Interop.Outlook.Application();
ns = app.GetNamespace("MAPI");
ns.Logon(EmailID, password, true, true);
inboxFolder = ns.Folders[EmailID].Folders[2];
foreach (Microsoft.Office.Interop.Outlook.MailItem mailItemm in inboxFolder.Items)
{
if (mailItemm.UnRead) // I only process the mail if unread
{
// Email Subject
Console.WriteLine("Subject : {0}", mailItemm.Subject);
string Subject = mailItemm.Subject;
if (!string.IsNullOrEmpty(Subject) && !string.IsNullOrWhiteSpace(Subject))
{
if (Subject.Contains(FileDomain))
{
var SenderName = mailItemm.Sender.Name;
//Email Body
Console.WriteLine("Accounts: {0}", mailItemm.Body);
// Read All Attachements
var attachments = (mailItemm as MailItem).Attachments;
if (attachments != null && attachments.Count > 0)
{
for (int i = 1; i <= attachments.Count; i++)
{
attachments[i].SaveAsFile(tempFolderPath + (mailItemm as MailItem).Attachments[i].FileName);
}
}
}
}
}
}
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
ns.Logoff();
inboxFolder = null;
subFolder = null;
mailItem = null;
app = null;
}
}
Using ExchangeService service
public static void Cloud_OutLookMailStart(string EmailID, string password, string StoreFilePath)
{
try
{
LogHelper.LogMessage("<----- Cloud_OutLookMailStart Start ----->");
DistributionReplyEntity ObjDistributionReplyEntity = new DistributionReplyEntity();
ObjDistributionReplyEntity.OutLookEmailID = EmailID;
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
service.Credentials = new WebCredentials(EmailID, password);
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
//service.Url = new Uri("https://IP/EWS/Exchange.asmx");
service.AutodiscoverUrl(EmailID, RedirectionUrlValidationCallback);
Microsoft.Exchange.WebServices.Data.Folder inbox = Microsoft.Exchange.WebServices.Data.Folder.Bind(service, WellKnownFolderName.Inbox);
var items = service.FindItems(
//Find Mails from Inbox of the given Mailbox
new FolderId(WellKnownFolderName.Inbox, new Mailbox(EmailID)),
//Filter criterion
// new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter[] {
// new SearchFilter.ContainsSubstring(ItemSchema.Subject, ConfigurationManager.AppSettings["ValidEmailIdentifier"].ToString()),
new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false),
// }),
//View Size as 15
new ItemView(50));
Console.WriteLine("Email {0}, unread Total Count{1}", EmailID, items.Count());
foreach (Item item in items)
{
EmailMessage email = EmailMessage.Bind(service, new ItemId(item.Id.UniqueId.ToString()));
if (!string.IsNullOrEmpty(email.Subject) && !string.IsNullOrWhiteSpace(email.Subject))
{
var subject = email.Subject.ToString();
String[] arr = subject.Split(' ');
String firstWord = arr[0];
if (firstWord != "Undeliverable:")
{
//PROCESS EMAIL MESSAGE
Console.WriteLine("Subject :{0}", email.Subject);
// TO
if (email.ToRecipients.Count > 0)
{
var propertySet = new PropertySet(ItemSchema.UniqueBody);
EmailMessage email2 = EmailMessage.Bind(service, email.Id, propertySet);
EmailMessage str = (EmailMessage)email2;
string str1 = str.UniqueBody.Text.ToString();
var EmailBody = ExtractReply(str1, "");
// string ReceiverEmail = email.ReceivedBy != null?email.ReceivedBy.Address:"" ;
// Email Body
// var subjectEmail = ExtractReply(email.Body.ToString(), email.ReceivedBy.Address);
Console.WriteLine("Body {0}", EmailBody.ToString()); // Body
ObjDistributionReplyEntity.EmailBody = EmailBody;
string maltipleTo = string.Empty;
foreach (var toemailid in email.ToRecipients)
{
if (string.IsNullOrEmpty(maltipleTo))
{
maltipleTo = toemailid.Address.ToString();
}
else
{
maltipleTo += ";" + toemailid.Address.ToString();
}
}
Console.WriteLine("TO {0}", maltipleTo.ToString()); // TO
ObjDistributionReplyEntity.ReplyTO = maltipleTo.ToString();
}
// CC
if (email.CcRecipients.Count > 0)
{
string maltipleCC = string.Empty;
foreach (var ccemailid in email.CcRecipients)
{
if (string.IsNullOrEmpty(maltipleCC))
{
maltipleCC = ccemailid.Address.ToString();
}
else
{
maltipleCC += ";" + ccemailid.Address.ToString();
}
}
Console.WriteLine("CC {0}", maltipleCC.ToString());
ObjDistributionReplyEntity.ReplyCC = maltipleCC.ToString();
}
// Form
if (email.Sender.Address != "")
{
ObjDistributionReplyEntity.ReplyForm = email.Sender.Address;
}
Console.WriteLine("Subject {0}", email.Subject.ToString()); // Subject
ObjDistributionReplyEntity.Subject = email.Subject.ToString();
ObjDistributionReplyEntity.TransactionsID = 0;
ObjDistributionReplyEntity.IsProjectRelated = 0;
string Subject = email.Subject;
ObjDistributionReplyEntity.ReceivedTime = email.DateTimeReceived;
var getSharePointFileUrl = GetAttachmentsFromEmail(service, item.Id, StoreFilePath, ObjDistributionReplyEntity.TransactionsID);
email.IsRead = true;
email.Update(ConflictResolutionMode.AlwaysOverwrite);
}
}
}
LogHelper.LogMessage("<----- Cloud_OutLookMailStart Start ----->");
}
catch (Exception ex)
{
LogHelper.LogError("OutLookMailStart -> Cloud_OutLookMailStart Exception");
LogHelper.LogError("Exception Message :" + ex.Message);
if (ex.InnerException != null)
{
LogHelper.LogError("Exception InnerException :" + ex.InnerException);
}
LogHelper.LogError("Exception StackTrace :" + ex.StackTrace);
LogHelper.LogError("OutLookMailStart -> Cloud_OutLookMailStart Exception");
}
}
public static string GetAttachmentsFromEmail(ExchangeService service, ItemId itemId, string StoreFilePath, Int64 TransactionsID)
{
try
{
LogHelper.LogMessage("<----- GetAttachmentsFromEmail Start ----->");
// Bind to an existing message item and retrieve the attachments collection.
// This method results in an GetItem call to EWS.
EmailMessage message = EmailMessage.Bind(service, itemId, new PropertySet(ItemSchema.Attachments));
List<ResponseMessage> ObjResponseMessage = new List<ResponseMessage>();
// Iterate through the attachments collection and load each attachment.
foreach (Attachment attachment in message.Attachments)
{
if (attachment is FileAttachment)
{
FileAttachment fileAttachment = attachment as FileAttachment;
// Load the attachment into a file.
// This call results in a GetAttachment call to EWS.
fileAttachment.Load(StoreFilePath + fileAttachment.Name);
string FileName = fileAttachment.Name;
LogHelper.LogMessage("OutLookMailStart In attachments File Name :" + FileName );
Console.WriteLine("File attachment name: " + fileAttachment.Name);
}
else // Attachment is an item attachment.
{
ItemAttachment itemAttachment = attachment as ItemAttachment;
// Load attachment into memory and write out the subject.
// This does not save the file like it does with a file attachment.
// This call results in a GetAttachment call to EWS.
itemAttachment.Load();
Console.WriteLine("Item attachment name: " + itemAttachment.Name);
}
}
}
catch (Exception ex)
{
LogHelper.LogError("OutLookMailStart -> GetAttachmentsFromEmail Exception");
LogHelper.LogError("Exception Message :" + ex.Message);
if (ex.InnerException != null)
{
LogHelper.LogError("Exception InnerException :" + ex.InnerException);
}
LogHelper.LogError("Exception StackTrace :" + ex.StackTrace);
LogHelper.LogError("OutLookMailStart -> GetAttachmentsFromEmail Exception"); ;
}
LogHelper.LogMessage("<----- GetAttachmentsFromEmail End ----->");
}
I am trying to access a second mailbox in outlook using an ExchangeService. but when I run the application it grabs my main email. Its worth noting that I use windows authentication here, and that I need to for this to work.
var useExchangeServer = new UseExchangeServer("SECONDEMAIL#mycompany.com");
var messages = useExchangeServer.LoadMessages(1);
foreach (var message in messages){ //At this point message has the wrong email...
...
}
here is my "UseExchangeServer" class
public UseExchangeServer(string mailBox)
{
_service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
_service.UseDefaultCredentials = true;
_service.AutodiscoverUrl(mailBox);
}
public FindItemsResults<Item> GetLastItems(int numberOfItems)
{
return _service.FindItems(WellKnownFolderName.Inbox, new ItemView(numberOfItems));
}
public IEnumerable<EmailMessage> LoadMessages(int numberOfMessages)
{
var findResults = GetLastItems(numberOfMessages);
foreach (var item in findResults.Items)
{
var message = EmailMessage.Bind(_service, item.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments));
message.Load();
yield return message;
}
}
You need to use the FolderId overload to specify the Mailbox you want to access otherwise the Mailbox that belongs to the credentials you are using will be used so you will need to do something like the following with your code
public UseExchangeServer(string mailBox)
{
_service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
_service.UseDefaultCredentials = true;
_service.AutodiscoverUrl(mailBox);
}
public FindItemsResults<Item> GetLastItems(int numberOfItems,string mailBox)
{
FolderId FolderToAccess = new FolderId(WellKnownFolderName.Inbox,mailBox);
return _service.FindItems(FolderToAccess, new ItemView(numberOfItems));
}
public IEnumerable<EmailMessage> LoadMessages(int numberOfMessages)
{
var findResults = GetLastItems(numberOfMessages);
foreach (var item in findResults.Items)
{
var message = EmailMessage.Bind(_service, item.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments));
message.Load();
yield return message;
}
}
Cheers
Glen
I'm trying to set up an IMAP server which is pulling data from a SQL database.
I've got the messages working no problems, but I can't work out how to attach attachments to them.
The attachments object on the Mail_Message object also only has a getter and a method called GetAttachments() which doesn't seem to connect to anywhere.
My current code is:
//this is my own object I'm using to pull data from the database
var cmMsg = _ml.GetMessage(mId, session.AuthenticatedUserIdentity.Name, -1);
var msgBody = new MIME_b_Text(MIME_MediaTypes.Text.html);
var msg = new Mail_Message();
msg.Body = msgBody;
msg.To = new Mail_t_AddressList();
msg.From = new Mail_t_MailboxList {new Mail_t_Mailbox(cmMsg.From, cmMsg.FromEmail)};
msg.Cc = new Mail_t_AddressList();
msg.Bcc = new Mail_t_AddressList();
foreach (var recipient in cmMsg.Recipients)
{
if (recipient.isTo)
{
msg.To.Add(new Mail_t_Mailbox(recipient.FullName, recipient.SMTPAddress));
}
else if(recipient.isCC)
{
msg.Cc.Add(new Mail_t_Mailbox(recipient.FullName, recipient.SMTPAddress));
}
else if (recipient.isBCC)
{
msg.Bcc.Add(new Mail_t_Mailbox(recipient.FullName, recipient.SMTPAddress));
}
}
//I tried adding a setter to the attachment object, but just get errors with this code
var a = new List<MIME_Entity>();
foreach (var attachment in cmMsg.Attachments)
{
var aCT = new MIME_b_Multipart(new MIME_h_ContentType("application/octet-stream"));
a.Add(new MIME_Entity
{
Body = aCT,
ContentDisposition = new MIME_h_ContentDisposition("attachment"),
});
}
msg.Attachments = a.ToArray();
msg.Subject = cmMsg.Subject;
msg.Date = cmMsg.TimeDate;
msg.MessageID = cmMsg.InternetMessageId;
if (e.FetchDataType == IMAP_Fetch_DataType.MessageStructure)
{
}
else if(e.FetchDataType == IMAP_Fetch_DataType.MessageHeader)
{
}
else
{
msgBody.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, cmMsg.HtmlBody);
_da.MarkAsRead(archiveID, session.AuthenticatedUserIdentity.Name);
}
e.AddData(info, msg);
I'm not sure if I'm missing something or just got this set up wrong. I noticed there was a MySQL API in the example projects, but that didn't have anything to do with attachments in it either.
Ok so turns out I was going about it the complete wrong way. Below is the code required
Effectively, it requires setting the message to be multipart mixes instead of just text. You can then add the attachments as a body part.
var cmMsg = _ml.GetMessage(mId, session.AuthenticatedUserIdentity.Name, -1);
MIME_h_ContentType contentType_multipartMixed = new MIME_h_ContentType(MIME_MediaTypes.Multipart.mixed);
contentType_multipartMixed.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.');
MIME_b_MultipartMixed multipartMixed = new MIME_b_MultipartMixed(contentType_multipartMixed);
var msg = new Mail_Message();
msg.To = new Mail_t_AddressList();
msg.From = new Mail_t_MailboxList {new Mail_t_Mailbox(cmMsg.From, cmMsg.FromEmail)};
msg.Cc = new Mail_t_AddressList();
msg.Bcc = new Mail_t_AddressList();
msg.Body = multipartMixed;
foreach (var recipient in cmMsg.Recipients)
{
if (recipient.isTo)
{
msg.To.Add(new Mail_t_Mailbox(recipient.FullName, recipient.SMTPAddress));
}
else if(recipient.isCC)
{
msg.Cc.Add(new Mail_t_Mailbox(recipient.FullName, recipient.SMTPAddress));
}
else if (recipient.isBCC)
{
msg.Bcc.Add(new Mail_t_Mailbox(recipient.FullName, recipient.SMTPAddress));
}
}
msg.Subject = cmMsg.Subject;
msg.Date = cmMsg.TimeDate;
msg.MessageID = cmMsg.InternetMessageId;
msg.MimeVersion = "1.0";
msg.Header.Add(new MIME_h_Unstructured("X-MS-Has-Attach", "yes"));
if (e.FetchDataType == IMAP_Fetch_DataType.MessageStructure)
{
}
else if(e.FetchDataType == IMAP_Fetch_DataType.MessageHeader)
{
}
else
{
MIME_Entity entity_text_plain = new MIME_Entity();
MIME_b_Text text_plain = new MIME_b_Text(MIME_MediaTypes.Text.plain);
entity_text_plain.Body = text_plain;
text_plain.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, cmMsg.HtmlBody);
multipartMixed.BodyParts.Add(entity_text_plain);
foreach (var attachment in cmMsg.Attachments)
{
using (var fs = new FileStream(#"C:\test.txt", FileMode.Open))
{
multipartMixed.BodyParts.Add(Mail_Message.CreateAttachment(fs, "test.txt"));
}
}
}
e.AddData(info, msg);