My application sends a templated email with information from a datagridview.
I am trying to send a follow up email.
I'd like the app to open the existing email from my sent items folder (using Outlook 365/Outlook 16) and add text to the top of the already existing email so there's a clear chain of communication.
I have code to find the email within the sent box.
How do I open/display that email so text can be added onto it before it's forwarded?
What I have so far:
private void dvgLogs_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
label4.Visible = true;
Outlook.Application app = new Outlook.Application();
Outlook.Selection item = app.ActiveExplorer().Selection;
Outlook.Folder sentItems = (Outlook.Folder)app.ActiveExplorer().Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderSentMail);
Outlook.Items items = sentItems.Items;
Outlook.MailItem mailItem = null;
object folderItem;
string subjectName = "Regarding " + dgvTickets.CurrentRow.Cells[2].Value.ToString() + " #" + dgvTickets.CurrentRow.Cells[3].Value.ToString();
string filter = "[Subject] = " + subjectName;
folderItem = items.Find(filter);
while (folderItem != null)
{
mailItem = folderItem as Outlook.MailItem;
if (mailItem != null)
{
subjectName += mailItem.Subject;
}
folderItem = items.FindNext();
}
subjectName = " The following e-mail messages were found: " + subjectName;
MessageBox.Show(subjectName);
lblFoundEmail.Text = subjectName;
}
This seems to find the email and let me know that it found it in my messagebox.
I want it to open the found email.
EDIT
This code is not quite what I want, but it's better than the above code where my email was not being displayed.
private void button1_Click(object sender, EventArgs e)
{
Outlook.Application app = new Outlook.Application();
Outlook.Selection item = app.ActiveExplorer().Selection;
Outlook.Folder sentItems = (Outlook.Folder)app.ActiveExplorer().Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderSentMail);
if (app.Session.DefaultStore.IsInstantSearchEnabled)
{
Outlook.Explorer explorer = (Explorer)app.Explorers.Add(item.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderSentMail)
as Outlook.Folder, Outlook.OlFolderDisplayMode.olFolderDisplayNormal);
string subjectName = "Regarding " + dgvTickets.CurrentRow.Cells[2].Value.ToString() + " #" + dgvTickets.CurrentRow.Cells[3].Value.ToString();
string filter = "subject:" + "\"" + subjectName + "\"";
explorer.Search(filter, Outlook.OlSearchScope.olSearchScopeAllFolders);
explorer.Display();
}
}
The above code appears to pop open a new Outlook window, and perform the search (which is more than what it was doing, also, it does find the sent email each time), however it doesn't display the email, instead just another instance of Outlook with the performed search.
I'd like it to use the Outlook window that's already open, and then display the found email.
Related
I have successfully read the .pst files thorough C#.
The issue is if a mail has multiple recipient (i.e. sender email address) then I am not able to get those multiple address. with the code
Outlook.Application app = new Outlook.Application();
Outlook.NameSpace outlookNs = app.GetNamespace("MAPI");
outlookNs.AddStore(#"D:\pst\Test.pst");
Outlook.MAPIFolder emailFolder = outlookNs.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderSentMail);
List<MailItem> lstMails = emailFolder.Items.OfType<MailItem>().Where(x=>x.SenderEmailAddress.Contains("hari")).Select(x=>x).ToList();
foreach (Object obj in emailFolder.Items)
{
if(obj is MailItem)
{
MailItem item = (MailItem)obj;
Console.WriteLine(item.SenderEmailAddress + " " + item.Subject + "\n" + item.Body);
}
}
item.SenderEmailAddress is returning a very strange address for multiple recipient, also if i have made any group of people and send mail to them then also.
So any one can guide how to read those multiple address and also the name of the group.
Thanks in advance.
Try this
Outlook.Application app = new Outlook.Application();
Outlook.NameSpace outlookNs = app.GetNamespace("MAPI");
outlookNs.AddStore(#"D:\pst\Test.pst");
Outlook.MAPIFolder emailFolder = outlookNs.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderSentMail);
List<MailItem> lstMails = emailFolder.Items.OfType<MailItem>().Where(x=>x.SenderEmailAddress.Contains("hari")).Select(x=>x).ToList();
foreach (Object obj in emailFolder.Items)
{
if(obj is MailItem)
{
MailItem item = (MailItem)obj;
String user=String.Empty;
foreach (Object obj1 in ((dynamic)item).Recipients)
{
user += ((dynamic)obj1).Name + ";";
}
Console.WriteLine(user + " " + item.Subject + "\n" + item.Body);
}
}
This has worked for me.
As a note, do not use LINQ with Outlook. It might look cool in your code, but you need to realize that all the processing is done on the client side, it is not any different from explicitly looping through all items in the folder.
Use Items.Restrict or Find/FindNext - the search will be performed by the store provider.
I have the following code:
string imageSrc = "C:\\Documents and Settings\\menonsu\\Desktop\\screenScrapper\\Bitmap1.bmp";
oMsg.HTMLBody = "<HTML><BODY><img src = \" cid:Bitmap1.bmp#embed \"/><br><font size=\"2\" face=\"Courier New\">" + introText + "</font>" + body + "<font size=\"2\" face=\"Courier New\">" + conclText + "</font>" + " </BODY></HTML>";
Microsoft.Office.Interop.Outlook.Attachment attc = oMsg.Attachments.Add(imageSrc, Microsoft.Office.Interop.Outlook.OlAttachmentType.olEmbeddeditem, null, "");
attc.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001E", "Bitmap1.bmp#EMBED");
//Send the message.
oMsg.Save();
For some reason the email is just showing an x when i try to run this code...anyone know why?
The following is working code with two ways of achieving this:
using System;
using Outlook = Microsoft.Office.Interop.Outlook;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
Method1();
Method2();
}
public static void Method1()
{
Outlook.Application outlookApp = new Outlook.Application();
Outlook.MailItem mailItem = outlookApp.CreateItem(Outlook.OlItemType.olMailItem);
mailItem.Subject = "This is the subject";
mailItem.To = "john#example.com";
string imageSrc = "D:\\Temp\\test.jpg"; // Change path as needed
var attachments = mailItem.Attachments;
var attachment = attachments.Add(imageSrc);
attachment.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x370E001F", "image/jpeg");
attachment.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F", "myident"); // Image identifier found in the HTML code right after cid. Can be anything.
mailItem.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/id/{00062008-0000-0000-C000-000000000046}/8514000B", true);
// Set body format to HTML
mailItem.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;
string msgHTMLBody = "<html><head></head><body>Hello,<br><br>This is a working example of embedding an image unsing C#:<br><br><img align=\"baseline\" border=\"1\" hspace=\"0\" src=\"cid:myident\" width=\"\" 600=\"\" hold=\" /> \"></img><br><br>Regards,<br>Tarik Hoshan</body></html>";
mailItem.HTMLBody = msgHTMLBody;
mailItem.Send();
}
public static void Method2()
{
// Create the Outlook application.
Outlook.Application outlookApp = new Outlook.Application();
Outlook.MailItem mailItem = (Outlook.MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem);
//Add an attachment.
String attachmentDisplayName = "MyAttachment";
// Attach the file to be embedded
string imageSrc = "D:\\Temp\\test.jpg"; // Change path as needed
Outlook.Attachment oAttach = mailItem.Attachments.Add(imageSrc, Outlook.OlAttachmentType.olByValue, null, attachmentDisplayName);
mailItem.Subject = "Sending an embedded image";
string imageContentid = "someimage.jpg"; // Content ID can be anything. It is referenced in the HTML body
oAttach.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001E", imageContentid);
mailItem.HTMLBody = String.Format(
"<body>Hello,<br><br>This is an example of an embedded image:<br><br><img src=\"cid:{0}\"><br><br>Regards,<br>Tarik</body>",
imageContentid);
// Add recipient
Outlook.Recipient recipient = mailItem.Recipients.Add("john#example.com");
recipient.Resolve();
// Send.
mailItem.Send();
}
}
}
From what I can tell, you are not setting the content id properly. Try to change the code to the following:
attc.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x370E001F", "image/bmp");
attc.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F", "Bitmap1.bmp#EMBED");
I have done this before a little differently. I embedded images in some emails that I had to send from my web app using an 'alternate view' in the system.net.mail
System.Net.Mail.LinkedResource theContent = new System.Net.Mail.LinkedResource({path to image});
theContent.ContentID = "TheContent";
String altViewString = anEmail.Body.replace("{original imageSource i.e. '../Images/someimage.gif'}","cid:TheContent");
System.Net.Mail.AlternateView altView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(altViewString, Nothing, System.Net.Mime.MediaTypeNames.Text.Html);
altView.LinkedResources.add(theContent);
anEmail.Message.AlternateViews.Add(altView);
Here's a simple solution:
private static void insertPictureAsLink(Outlook.MailItem mail, String imagePath, String URI)
{
mail.BodyFormat = OlBodyFormat.olFormatHTML;
mail.HTMLBody += String.Format("<body></body>", imagePath, URI);
mail.Display(false);
}
I'm developing a desktop application that has mail sending option. I have the following code to that and it works perfect for only 1 recipient:
DialogResult status;
status = MessageBox.Show("Some message", "Info", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
if (status == DialogResult.OK)
{
try
{
// Create the Outlook application.
Outlook.Application oApp = new Outlook.Application();
// Create a new mail item.
Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
// Set HTMLBody.
//add the body of the email
oMsg.HTMLBody = "<html>" +
"<body>" +
"some html text" +
"</body>" +
"</html>";
int iPosition = (int)oMsg.Body.Length + 1;
//Subject line
oMsg.Subject = txt_mailKonu.Text;
oMsg.Importance = Outlook.OlImportance.olImportanceHigh;
// Recipient
Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
//Following line causes the problem
Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add(senderForm.getRecipientList().ToString());
oRecip.Resolve();
//oRecip.Resolve();
// Send.
oMsg.Send();
// Clean up.
oRecip = null;
oRecips = null;
oMsg = null;
oApp = null;
MessageBox.Show("Successful", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception)
{
MessageBox.Show("Failed", "Eror", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
I get the error at the bold line where I'm adding multiple recipients in the following pattern:
john.harper#abcd.com; adam.smith#abcd.com
It works fine for 1 address but when I get multiple addresses separated it throws COM Exception - Outlook cannot resolve one or more names.
Hope you'll help me with this.
Did you try to add multiple recipients to oMsg.Recipients?
// I assume that senderForm.getRecipientList() returns List<String>
foreach(String recipient in senderForm.getRecipientList())
{
Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add(recipient);
oRecip.Resolve();
}
If needed, you could explode senderForm.getRecipientList().ToString() with
String [] rcpts = senderForm.getRecipientList().ToString().Split(new string[] { "; " }, StringSplitOptions.None);
and use new object in foreach loop.
I have a requirement to send automated emails based on a template saved at path :
HostingEnvironment.MapPath("~/Content/emailTemplate/emailTemplate.oft")
I am using code below to accomplishis this, it works fine without template by using (oApp.CreateItem()), but when i use
oApp.CreateItemFromTemplate() instead of oApp.CreateItem() i get exception.
public static void CreateMessageWithAttachment(
string invoiceNumber, string recipient, string messageBody)
{
Outlook.Application oApp = new Outlook.Application();
Outlook.Folders folder = oApp.Session.GetDefaultFolder(
Outlook.OlDefaultFolders.olFolderDrafts)
as Outlook.Folders;
Outlook.MailItem email = oApp.CreateItemFromTemplate(
HostingEnvironment.MapPath(
"~/Content/emailTemplate/emailTemplate.oft"), folder)
as Outlook.MailItem;
email.Recipients.Add(recipient);
email.Subject = "Invoice # " + invoiceNumber;
{
string fileName = invoiceNumber.Trim();
string filePath = HostingEnvironment.MapPath("~/Content/reports/");
filePath = filePath + fileName + ".pdf";
fileName += ".pdf";
int iPosition = (int)email.Body.Length + 1;
int iAttachType = (int)Outlook.OlAttachmentType.olByValue;
Outlook.Attachment oAttach = email.Attachments.Add(
filePath, iAttachType, iPosition, fileName);
}
email.Display();
////..uncomment below line to SendAutomatedEmail emails atomaticallly
////((Outlook.MailItem)email).Send();
}
//use this as a example I wonder if the network path has issues being resolved what error
//are you getting as well
"~/Content/emailTemplate/emailTemplate.oft" you need to get the relative path on the network too. replace the sample below with your values and variables.
private void CreateItemFromTemplate()
{
Outlook.Folder folder =
Application.Session.GetDefaultFolder(
Outlook.OlDefaultFolders.olFolderDrafts) as Outlook.Folder;
Outlook.MailItem mail =
Application.CreateItemFromTemplate(
#""~/Content/emailTemplate/emailTemplate.oft", folder) as Outlook.MailItem;
mail.Subject = "Congratulations";
mail.Save();
}
I currently have existing code that automates and email and sends files. I now need to add a cc. I have looked all over, but can't seem to find out with my existing code. Any help would be greatly appreciated. Thank you.
private void button13_Click(object sender, EventArgs e)
{
//Send Routing and Drawing to Dan
// Create the Outlook application by using inline initialization.
Outlook.Application oApp = new Outlook.Application();
//Create the new message by using the simplest approach.
Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
//Add a recipient
Outlook.Recipient oRecip = (Outlook.Recipient)oMsg.Recipients.Add("email#email.com");
oRecip.Resolve();
//Set the basic properties.
oMsg.Subject = "Job # " + textBox9.Text + " Release (" + textBox1.Text + ")";
oMsg.HTMLBody = "<html><body>";
oMsg.HTMLBody += "Job # " + textBox9.Text + " is ready for release attached is the Print and Routing (" + textBox1.Text + ")";
oMsg.HTMLBody += "<p><a href='C:\\Users\\RussellS\\Desktop\\Russell Eng Reference\\" + textBox1.Text + ".PDF'>" + textBox1.Text + " Drawing";
oMsg.HTMLBody += "<p><a href='C:\\Users\\RussellS\\Desktop\\" + textBox1.Text + ".PDF'>" + textBox1.Text + " Routing" + "</a></p></body></html>";
//Send the message
oMsg.Send();
//Explicitly release objects.
oRecip = null;
oMsg = null;
oApp = null;
MessageBox.Show(textBox1.Text + " Print and Routing Sent");
}
According to MSDN there's a CC property on the MailItem class.
string CC { get; set; }
Which can be used to set the names of the CC recipients.
http://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook._mailitem.cc.aspx
To modify the recipients you can add them to the Recipients collection:
http://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook.recipients.aspx
Which you would use like:
oMsg.Recipients.Add("foo#bar.com");
Please follow this code for adding CC and BCC:
private void SetRecipientTypeForMail()
{
Outlook.MailItem mail = Application.CreateItem(
Outlook.OlItemType.olMailItem) as Outlook.MailItem;
mail.Subject = "Sample Message";
Outlook.Recipient recipTo =
mail.Recipients.Add("someone#example.com");
recipTo.Type = (int)Outlook.OlMailRecipientType.olTo;
Outlook.Recipient recipCc =
mail.Recipients.Add("someonecc#example.com");
recipCc.Type = (int)Outlook.OlMailRecipientType.olCC;
Outlook.Recipient recipBcc =
mail.Recipients.Add("someonebcc#example.com");
recipBcc.Type = (int)Outlook.OlMailRecipientType.olBCC;
mail.Recipients.ResolveAll();
mail.Display(false);
}