Microsoft Outlook adding cc to email - c#

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);
}

Related

How to open an email, in the sent box, with C#?

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.

Adding table using mailto and windows forms

I want to open mail to and inside the body of my email I want to create a table and insert values inside my model. So I execute outlook like this:
var mail = $"mailto:test#test.com?subject=ProjectListTest&body={finalString}";
My question is, how can I create a table and add to body of mailto?
Table headers: Name, Customer
so inside each row I want to use something like:
var finalString = string.Empty;
foreach(var customer in CustomerList)
{
finalString = finalString + customer.Name + customer.CustomerKey
}
Is it possible to achieve this? what is the correct format to create a table in Outlook. Regards
pIf the table would be created using the html mail body format, then you can use the following method to generate it:
public string GenerateMailBodyWithTable(List<Customer> customers)
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append($"<html>{ Environment.NewLine }<body>{ Environment.NewLine }");
if (customers.Count > 0)
{
stringBuilder.Append($"<table><tr><th>Name</th><th>Key</th></tr>{ Environment.NewLine }");
foreach (Customer customer in customers)
{
stringBuilder.Append($"<tr><th>{ customer._name }</th><th>{ customer._key }</th></tr>{ Environment.NewLine }");
}
stringBuilder.Append($"<table>{ Environment.NewLine }");
}
else
{
stringBuilder.Append($"<p>No customers<p>{ Environment.NewLine }");
}
stringBuilder.Append($"</html>{ Environment.NewLine }</body>");
return stringBuilder.ToString();
}
After generating the html body you can perform the following action to fill the mailbody:
Outlook.Application outlookApp = new Outlook.Application();
Outlook.MailItem mailMessage = (Outlook.MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem);
mailMessage.HTMLBody = GenerateMailBodyWithTable(customers);
mailMessage.Display(true);
Don't forget to place this using statement:
using Outlook = Microsoft.Office.Interop.Outlook;
First at all, you have to create your custom HTML:
string finalString = "<table><tr><td><b>Name</b></td><td><b>Customer</b></td></tr>";
foreach(var customer in CustomerList)
{
finalString += "<tr><td>" + customer.Name + "</td><td>" + customer.CustomerKey + "</td></tr>";
}
finalString += "</table>";
If you are using WinForms and you want to send an email with this body, you can use MailMessage Class from System.Net.Mail and sending it with SmtpClient. This way:
MailMessage mail = new MailMessage("from", "mailto", "Subject", finalString);
mail.IsBodyHtml = true; //Important
SmtpClient smtp = new SmtpClient("serverSMTP");
smtp.EnableSsl = USE_SSL;
smtp.Port = YOUR_PORT;
smtp.Credentials = new System.Net.NetworkCredential("email", "password");
smtp.Send(correo);
If you want to simulate a "mailto" action, you can use:
string command = $"mailto:test#test.com?subject=ProjectListTest&body={finalString}";
Process.Start(command);
Regards

Change text to Bold in Outlook Message Body

please help me with following.
I'm working on creating and modifying outlook messages from template. I need to change some text to Bold.
foreach (XmlNode node in nodeList)
{
string CustomerName = node.SelectSingleNode("CustomerName").InnerText;
string ReportName = node.SelectSingleNode("ReportName").InnerText + ".pdf";
Outlook.Application mailApplication = new Outlook.Application();
Outlook.MailItem mail = mailApplication.CreateItemFromTemplate(#"d:\Friday Report\#TEMPLATES\template.oft") as Outlook.MailItem;
mail.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;
mail.Attachments.Add(#"d:\Friday Report\" + ReportName);
mail.Subject = "Application Packaging – Weekly Summary";
CustomerName = "<b>" + CustomerName + "</b> ";
string body = mail.Body;
string new_body = body.Replace("CustomerName", CustomerName );
mail.Body = new_body;
mail.Display(true);
mail.Close(Outlook.OlInspectorClose.olDiscard);
}
If you want to use HTML in your email, you need to set the HTMLBody property instead of Body:
foreach (XmlNode node in nodeList)
{
string CustomerName = node.SelectSingleNode("CustomerName").InnerText;
string ReportName = node.SelectSingleNode("ReportName").InnerText + ".pdf";
Outlook.Application mailApplication = new Outlook.Application();
Outlook.MailItem mail = mailApplication.CreateItemFromTemplate(#"d:\Friday Report\#TEMPLATES\template.oft") as Outlook.MailItem;
mail.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;
mail.Attachments.Add(#"d:\Friday Report\" + ReportName);
mail.Subject = "Application Packaging – Weekly Summary";
CustomerName = "<b>" + CustomerName + "</b> ";
string body = mail.Body;
string new_body = body.Replace("CustomerName", CustomerName );
mail.HTMLBody = new_body;
mail.Display(true);
mail.Close(Outlook.OlInspectorClose.olDiscard);
}
You should use valid HTML, though, by surrounding your mail with <html><body>{your message}</body></html>
This seems to work (see screen shot below the code)
using Microsoft.Office.Interop.Outlook;
using outlookApp = Microsoft.Office.Interop.Outlook;
namespace z_Console_Scratch
{
class Program
{
static void Main(string[] args)
{
Microsoft.Office.Interop.Outlook.Application outlookApp = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MailItem mailItem = (Microsoft.Office.Interop.Outlook.MailItem)outlookApp.CreateItem(OlItemType.olMailItem);
mailItem.Subject = "test subject";
mailItem.HTMLBody = "<html><body>This is the <strong>funky</strong> message body</body></html>";
mailItem.Display(false);
}
}
}
Note: This works as well: mailItem.HTMLBody = "<html><body>This is the <b>funky</b> message body</body></html>";
Screen Shot

Property or indexer "Attachments" cannot be assigned to -- it is read only

I´m trying to send mail with image attachment, but it still throwing error
(*Property or indexer "Attachments" cannot be assigned to -- it is read only *)
string pathToPic = #"c:\MyDir\Img\img"+ automaticalyGeneratedNumber.toString() + ".png";
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = Environment.MachineName,
Body = "PC NAME : " + Environment.MachineName + "\r\nIP ADRESS : " + Dns.GetHostEntry(Dns.GetHostName()).AddressList[1],
Attachments = new Attachment(#"c:\MyDir\Img" + "/img" + (Saving.CountImagesTaken(#"c:\MyDir\Img") - 1).ToString() + ".png"),
})
{
smtp.Send(message);
}
Why complicate the code like that. You need to use message.Attachments.Add since the Attachments property is read-only :
var message = new MailMessage(fromAddress, toAddress)
{
Subject = Environment.MachineName,
Body = "PC NAME : " + Environment.MachineName + "\r\nIP ADRESS : " + Dns.GetHostEntry(Dns.GetHostName()).AddressList[1],
};
message.Attachments.Add(new Attachment(#"c:\MyDir\Img" + "/img" + (Saving.CountImagesTaken(#"c:\MyDir\Img") - 1).ToString() + ".png"));
using (message)
{
smtp.Send(message);
}

outlook mail object bcc

//Create the session.
Outlook.Application application = new Outlook.Application();
//Create the session.
Outlook.MailItem mail = application.CreateItem(Outlook.OlItemType.olMailItem) as Outlook.MailItem;
//create the receipents object
Outlook.Recipients objOutlookRecip = mail.Recipients;
while (Recipients.Read())
{
mail.Subject = Confirmations.GetString(2);
mail.Body = Confirmations.GetString(4) + ("\r\n");
mail.Body = mail.Body + ("\r\n") + Confirmations.GetString(5) + ("\r\n");
mail.Body = mail.Body + ("\r\n") + Confirmations.GetString(6);
mail.SentOnBehalfOfName = "user#email.com";
mail.Recipients.Add(Recipients.GetString(8));
}
Does anyone know how i might be able to insert the email addresses into bcc instead of the current process in the to field
Outlook.Recipient recipBcc =
mail.Recipients.Add(Recipients.GetString(8));
recipBcc.Type = (int)Outlook.OlMailRecipientType.olBCC;
check OlMailRecipientType Enumeration

Categories