So i need to get informations such as :
Sender mail address (to later get his Domain profile informations)
Mail subject (which should be the "filepath" minus the "msg" extension anyway).
And then, replying to it just like i would push "ReplyAll" button in Outlook. So the reply needs to get the usual Headers such as "From : ....", "To : ...", "Cc : ..." and so on.
All i need is to change its subject, and delete the address depending on the "FromAddress" of the user that will push the button
I've read a bit here and there, and people are talking about a MailItem, but there's no informations about HOW to get this item or how to build it from a .msg file.
What i have to do comes after a specific user action.
The user is supposed to Drag&Drop the mail into a panel, from there i get its local path.
Thanks for your time !
Edit#1
I managed to find out to get informations and to set a .msg file to a MailItem :
Outlook.Application appOutlook = new Outlook.Application();
var email = (Outlook.MailItem)appOutlook.Session.OpenSharedItem(filepath);
string getCC = "";
string getFrom = ""; // From is never null
string getTo = "";
string getSubject = "";
bool lengthCC = email.CC.HasValue();
bool lengthTo = email.To.HasValue();
bool lengthSubject = email.Subject.HasValue();
if (lengthCC)
{
getCC = email.CC.ToString();
}
// and so on...
//
// Display it in MessageBox to confirm test succeeded :
MessageBox.Show("CC : " + getCC +
"\nFrom : " + getFrom +
"\nTo : " + getTo +
"\nSubject : " + getSubject);
email.Close(Outlook.OlInspectorClose.olDiscard);
Now i just need to build the ReplyAll Body and add headers manually myself i guess...
Edit#2
No need to rewrite Headers apparently, doing so :
Outlook._MailItem reply = email.ReplyAll();
reply.To = getFrom;
reply.CC = getCC;
reply.Body = "SomeReplyMessage" + reply.Body;
reply.Send();
Marshal.ReleaseComObject(appOutlook);
Marshal.ReleaseComObject(email);
Marshal.ReleaseComObject(reply);
But it erased the separator above the original message, i'll find a way to re-add it !!!
Edit#3
And there it is, the so-called "separator" wasn't displaying, because i wasn't re-stating an HTML Body !
So, to keep it you can do this :
reply.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;
string ReplyMessageBody = String.Format("AddSome<br>HTMLCode<br>ThereAndHere<br>ButFinishWith : BodyTag</body>");
reply.HTMLBody = ReplyMessageBody + reply.HTMLBody;
Or simpler if you don't need your reply to be an HTML one :
reply.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;
reply.HTMLBody = "AddSomeReplyMessage" + reply.HTMLBody;
Outlook does not work directly wit MSG files - when you call CreateFromTemplate or even OpenSharedItem, Outlook creates a new item in its default store and imports the MSG or OFT file. It does not expose anything that would you let you figure out that the message came from a file; the item is indistinguishable from an item created directly using CreateItem or MAPIFolder.Items.Add.
See edits on original question for answer !
I'm creating an Outlook Add In, which has a subform. The form has a button on it, through which I would like to generate a mailitem, if the user clicks it. I'd like to auto-populate some info in the email, and then leave it for the user to send at their leisure.
My code looks like the following:
private void btnMailDocNotice_Click(object sender, EventArgs e)
{
string clientInfo = string.Empty;
string matInfo = string.Empty;
string author = string.Empty;
string dType = string.Empty;
string fLocation = string.Empty;
string keyWords = string.Empty;
string docName = string.Empty;
clientInfo = this.mCboClient.Text + " " + lblClient;
matInfo = this.mCboMatter.Text + " " + lblMatter;
author = this.txtAuthor.Text;
dType = this.mCboDocType.Text.ToUpper();
fLocation = this.txtSavePath.Text;
keyWords = this.txtKeyWords.Text;
docName = this.txtDocName.Text;
this.sendDocNotice = true;
this.Hide();
CreateMailItem(clientInfo, matInfo, author, dType, this.operatorCode.ToUpper(), fLocation, keyWords, docName);
this.Show();
}
private void CreateMailItem(string clientInfo, string matInfo, string author, string dType, string profiledBy, string fLocation, string keyWords, string docName)
{
this.DNoticeItem = (Outlook.MailItem)ThisAddIn.myApp.CreateItem(Outlook.OlItemType.olMailItem);
this.DNoticeItem.Subject = "Document: " + docName;
this.DNoticeItem.HTMLBody = "<span style=\"font-family:Calibri; font-size: 11pt;\">KeyWords: " + keyWords + "</span>";
this.DNoticeItem.HTMLBody += "<br />Client: " + clientInfo;
this.DNoticeItem.HTMLBody += "<br />Matter: " + matInfo;
this.DNoticeItem.HTMLBody += "<br />Author: " + author;
this.DNoticeItem.HTMLBody += "<br />Doc Type: " + dtClient;
this.DNoticeItem.HTMLBody += "<br />Profiled by: " + profiledBy;
this.DNoticeItem.HTMLBody += "<br />File://" + fLocation;
this.DNoticeItem.Importance = Outlook.OlImportance.olImportanceNormal;
this.DNoticeItem.Display(false);
}
The problem that I'm running into, is it fires an exception on the mailitem.display function, whether I use true or false (doing a bit of research says that determines if the user can access the main Outlook window or not while the mailitem is open). The exception is a COM Exception of "A dialog box is open. Close it and try again". I've tried hiding the WinForm prior to the function call that creates the mail item, then show it again after the function is exited, but it didn't work. I've tried a version of the code where I use System.Diagnostics.Process.Start() to try and open the file after saving it to disk, and while it doesn't fire an exception from the add in, Outlook prompts the user with a message box of the same message from the ComException. I even tried creating a field to see if the doc notice email should be drafted, and thought to have the code take care of that after a form.close() call, thinking the close call would at least dispose of the dialog box that was locking Outlook, and I still got the same exception.
Is there a way to achieve what I want? Does anyone have any suggestions? I'm kind of stuck at the moment, and would appreciate any help/pointers/suggestions anyone has to offer in this issue. My sincere apologies if this is a duplicative question - I couldn't find a good answer to the question. Thank you in advance for your time.
Firstly, why not display yoru own form modelessly?
Secondly (and this is pretty important) do not use code like the following
this.DNoticeItem.HTMLBody += "<br />Client: " + clientInfo;
Every time you run a line like that, you retrieve HTMLBody, add some stuff to it (making the HTML malformed), then set HTMLBody again and force Outlook to make sense of your (malformed) HTML. This (assuming Outlook can parse and fix your HTML) will result in HTML being returned to be different from what you set it to.
Build the HTML body once using a regular string, and set HTMLBody property only once.
I'm creating an application in C#. In this i can create a meeting request that is sent to the user through code and appears in Outlook mail.
The below code is what I am using to send the meeting invitation. It is working fine.
StringBuilder OutlookBody = new StringBuilder();
string textvs = #"BEGIN:VCALENDAR
PRODID:-//Microsoft Corporation//Outlook 10.0 MIMEDIR//EN
VERSION:1.0
BEGIN:VEVENT
LOCATION:" + Location + #"
DTSTART:" + string.Format("DTSTART:{0:yyyyMMddTHHmmssZ}", start) + #"
DTEND:" + string.Format("DTEND:{0:yyyyMMddTHHmmssZ}", end) + #"
DESCRIPTION;ENCODING=QUOTED-PRINTABLE:= " + OutlookBody + #"=0D=0A SUMMARY:" + AppoitmentName + #"
PRIORITY:3
END:VEVENT
END:VCALENDAR";
How can i use the same code to remove outlook meeting request.
I have also checked this answer, but it didn't solve my problem.
In OutLook every appointment/meeting will get a unique Id and a ChangeKey. A new ChangeKey is generated whenever there is a modification done to the meeting. To update an existing meeting you must have the Id and latest ChangeKey.
In your approach, if I am not wrong, you are just constructing an ICAL which is added to the outlook via email. In this case, you will not have the Id and ChangeKey to modify the meeting programatically. I would rather suggest you to change the approach.
If you have Microsoft Exchange the following links will guide. Else, ignore the links.
https://msdn.microsoft.com/en-us/library/office/dn495611(v=exchg.150).aspx
https://msdn.microsoft.com/en-us/library/office/dn495612(v=exchg.150).aspx
You can set the method and status of the meeting by adding these lines:
METHOD: CANCEL
STATUS: CANCELLED
See more here.
Use the following code
StringBuilder OutlookBody = new StringBuilder();
string textvs = #"BEGIN:VCALENDAR
PRODID:-//Microsoft Corporation//Outlook 10.0 MIMEDIR//EN
VERSION:1.0
BEGIN:VEVENT
LOCATION:" + Location + #"
DTSTART:" + string.Format("DTSTART:{0:yyyyMMddTHHmmssZ}", start) + #"
DTEND:" + string.Format("DTEND:{0:yyyyMMddTHHmmssZ}", end) + #"
DESCRIPTION;ENCODING=QUOTED-PRINTABLE:= " + OutlookBody + #"=0D=0A SUMMARY:" + AppoitmentName + #"
PRIORITY:3
METHOD:CANCEL
STATUS:CANCELLED
END:VEVENT
END:VCALENDAR";
And use the following Mime Type
System.Net.Mime.ContentType mimeType = new System.Net.Mime.ContentType("text/calendar; method=CANCEL");
AlternateView alternate = AlternateView.CreateAlternateViewFromString(body, mimeType);
message.AlternateViews.Add(alternate);
I solved this issue by changing some lines in code.
Change method from REQUEST to CANCEL ==> str.AppendLine("METHOD:CANCEL");
Change Status to Cancelled ==> str.AppendLine("STATUS:CANCELLED");
In System.Net.Mime.ContentType contype = newSystem.Net.Mime.ContentType("text/calendar"); change method from REQUEST to CANCEL ==> contype.Parameters.Add("method", "CANCEL");
I've developed an Outlook plugin using C# where for each new mail received, i get(and save) the sender/subject/the body of email & the attachments. Well, the last 2 gave me a headache. I can see the sender and the subject of the new mail but for the body&attachments it seems that is a problem. I've used NewMailEx for getting the new mails in Inbox. The function looks like this:
private void Application_NewMailEx(string EntryIDCollection)
{
string[] entryIdArray = EntryIDCollection.Split(',');
foreach (string entryId in entryIdArray)
{
try
{
Outlook.MailItem item = (Outlook.MailItem)Application.Session.GetItemFromID(EntryIDCollection, null);
string subj = item.Subject; //works
string to = item.To; //works
string bec = item.BCC; //does not work but dont care
string body = item.Body; //DOES NOT SAVE THE BODY OF THE NEW MAIL RECEIVED
string final = "Sender: " + item.SenderEmailAddress + "\r\n" + "Subject: " + subj + "\r\n" + "BCC: " + bec + "\r\n" + "TO: " + to + "\r\n\n" + "Body: " + body + "\r\n\n";
System.IO.File.AppendAllText(#"D:\tmp\atr.txt", final);
//the result of item.attachments.count is always 0 , even though I've
//sent mails with a different number of attachments. So the if
//statement is false
if (item.Attachments.Count > 0)
{
for (int i = 1; i <= item.Attachments.Count; i++)
{
item.Attachments[i].SaveAsFile(#"D:\tmp\" + item.Attachments[i].FileName);
}
}
Marshal.ReleaseComObject(item);
}
catch (System.Exception e)
{
MessageBox.Show(e.Message);
}
}
}
Where does the Item variable come from? You need to initialize it using Application.Session.getItemfromID().
I'm writing in VBA, so I feel like posting my code here would be a faux pas, but I have come to a solution using similar Object Libraries from the Outlook application that I think transfer well to your C++ intentions.
First of all, switching to POP3 certainly fixes this problem, but you're stuck using POP3, which is only ideal from a programming standpoint.
The solution I have found follows this algorithm:
//Generate Outlook MailItem Object, "item"
//If item.DownloadState is not 1,
//item.Display
//item.Close(1)
//Perform end of code operations
//Call Function that is identical to Application_NewMailEx but is not Application_NewMailEx because Application_NewMailEx is a function that is thrown during the incoming mail event.
//Else,
//Perform Intended Code
You see how calling a function identical to Application_NewMailEx creates a kind of loop because if item.DownloadState is not 1, you'll be calling that function again? I get that this isn't the most ideal coding practice, but I have scoured the internet and Outlook Application and Outlook Object Library experts have no idea how to solve this problem any other way (in fact, no one even proposes THIS solution)
For my full VBA Solution Check out:
https://superuser.com/questions/894972/outlook-strange-item-attachments-error/990968#990968
If create the body property as
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.Body ="First Line \n second line";
I also tried
message.Body ="First Line" + system.environment + "second line";
Both of these were ignored when I received the message (using outlook).
Any ideas on how to get mutliple lines? I am trying to avoid html encoding so that the email will play nicer with spam filters.
thanks
As per the comment by drris, if IsBodyHtml is set to true then a standard newline could potentially be ignored by design, I know you mention avoiding HTML but try using <br /> instead, even if just to see if this 'solves' the problem - then you can rule out by what you know:
var message = new System.Net.Mail.MailMessage();
message.Body = "First Line <br /> second line";
You may also just try setting IsBodyHtml to false and determining if newlines work in that instance, although, unless you set it to true explicitly I'm pretty sure it defaults to false anyway.
Also as a side note, avoiding HTML in emails is not necessarily any aid in getting the message through spam filters, AFAIK - if anything, the most you do by this is ensure cross-mail-client compatibility in terms of layout. To 'play nice' with spam filters, a number of other things ought to be taken into account; even so much as the subject and content of the mail, who the mail is sent from and where and do they match et cetera. An email simply won't be discriminated against because it is marked up with HTML.
In case you dont need the message body in html, turn it off:
message.IsBodyHtml = false;
then use e.g:
message.Body = "First line" + Environment.NewLine +
"Second line";
but if you need to have it in html for some reason, use the html-tag:
message.Body = "First line <br /> Second line";
Beginning each new line with two white spaces will avoid the auto-remove perpetrated by Outlook.
var lineString = " line 1\r\n";
linestring += " line 2";
Will correctly display:
line 1
line 2
It's a little clumsy feeling to use, but it does the job without a lot of extra effort being spent on it.
I usually like a StringBuilder when I'm working with MailMessage. Adding new lines is easy (via the AppendLine method), and you can simply set the Message's Body equal to StringBuilder.ToString() (... for the instance of StringBuilder).
StringBuilder result = new StringBuilder("my content here...");
result.AppendLine(); // break line
You need to enable IsBodyHTML
message.IsBodyHtml = true; //This will enable using HTML elements in email body
message.Body ="First Line <br /> second line";
The key to this is when you said
using Outlook.
I have had the same problem with perfectly formatted text body e-mails. It's Outlook that make trash out of it. Occasionally it is kind enough to tell you that "extra line breaks were removed". Usually it just does what it wants and makes you look stupid.
So I put in a terse body and put my nice formatted text in an attachement. You can either do that or format the body in HTML.
Try this
IsBodyHtml = false,
BodyEncoding = Encoding.UTF8,
BodyTransferEncoding = System.Net.Mime.TransferEncoding.EightBit
If you wish to stick to using \r\n
I managed to get mine working after trying for one whole day!
Try using the verbatim operator "#" before your message:
message.Body =
#"
FirstLine
SecondLine
"
Consider that also the distance of the text from the left margin affects on the real distance from the email body left margin..
Try using a StringBuilder object and use the appendline method. That might work.
Sometimes you don't want to create a html e-mail.
I solved the problem this way :
Replace \n by \t\n
The tab will not be shown, but the newline will work.
Today I found the same issue on a Error reporting app. I don't want to resort to HTML, to allow outlook to display the messages I had to do (assuming StringBuilder sb):
sb.Append(" \r\n\r\n").Append("Exception Time:" + DateTime.UtcNow.ToString());
I realise this may have been answered before. However, i had this issue this morning with Environment.Newline not being preserved in the email body.
The following is a full (Now Working with Environment.NewLine being preserved) method i use for sending an email through my program.(The Modules.MessageUpdate portion can be skipped as this just writes to a log file i have.) This is located on the main page of my WinForms program.
private void MasterMail(string MailContents)
{
Modules.MessageUpdate(this, ObjApp, EH, 3, 25, "", "", "", 0, 0, 0, 0, "Master Email - MasterMail Called.", "N", MainTxtDict, MessageResourcesTxtDict);
Outlook.Application OApp = new Outlook.Application();
//Location of email template to use. Outlook wont include my Signature through this automation so template contains only that.
string Temp = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + ResourceDetails.DictionaryResources("SigTempEmail", MainTxtDict);
Outlook.Folder folder = OApp.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderDrafts) as Outlook.Folder;
//create the email object.
Outlook.MailItem TestEmail = OApp.CreateItemFromTemplate(Temp, folder) as Outlook.MailItem;
//Set subject line.
TestEmail.Subject = "Automation Results";
//Create Recipients object.
Outlook.Recipients oRecips = (Outlook.Recipients)TestEmail.Recipients;
//Set and check email addresses to send to.
Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add("EmailAddressToSendTo");
oRecip.Resolve();
//Set the body of the email. (.HTMLBody for HTML Emails. .Body will preserve "Environment.NewLine")
TestEmail.Body = MailContents + TestEmail.Body;
try
{
//If outlook is not open, Open it.
Process[] pName = Process.GetProcessesByName("OUTLOOK.EXE");
if (pName.Length == 0)
{
System.Diagnostics.Process.Start(#"C:\Program Files\Microsoft Office\root\Office16\OUTLOOK.EXE");
}
//Send email
TestEmail.Send();
//Update logfile - Success.
Modules.MessageUpdate(this, ObjApp, EH, 1, 17, "", "", "", 0, 0, 0, 0, "Master Email sent.", "Y", MainTxtDict, MessageResourcesTxtDict);
}
catch (Exception E)
{
//Update LogFile - Fail.
Modules.MessageUpdate(this, ObjApp, EH, 5, 4, "", "", "", 0, 0, 0, 0, "Master Email - Error Occurred. System says: " + E.Message, "Y", MainTxtDict, MessageResourcesTxtDict);
}
finally
{
if (OApp != null)
{
OApp = null;
}
if (folder != null)
{
folder = null;
}
if (TestEmail != null)
{
TestEmail = null;
}
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
You can add multiple recipients by either including a "; " between email addresses manually, or in one of my other methods i populate from a Txt file into a dictionary and use that to create the recipients email addresses using the following snippet.
foreach (KeyValuePair<string, string> kvp in EmailDict)
{
Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add(kvp.Value);
RecipientList += string.Format("{0}; ", kvp.Value);
oRecip.Resolve();
}
I hope at least some of this helps someone.
Adding . before \r\n makes it work if the original string before \r\n has no .
Other characters may work. I didn't try.
With or without the three lines including IsBodyHtml, not a matter.
Something that worked for me was simply separating data with a :
message.Body = FirstLine + ":" + SecondLine;
I hope this helps