The question is how to write values from list to email body if I am getting the whole row as an output? Any suggestions how this should be done?
No errors, but also no output.
// Check if duplicates has been found = list is not empty. Write duplicates to Email message by creating a string with duplictes.
if (duplicatesPOSTADR?.Any() != false)
{
string combindedString = string.Join("\n", duplicatesPOSTADR);
string EmailBody = "There was an error and" +
"following duplicates has been found in POSTADR column: " + combindedString; // collect duplicate values to "combindedString"
CreateMailItem(EmailBody); // Create email message with body text
Console.WriteLine(EmailBody); // write to console
}
}
Output in outlook email should look like:
There was an error and following duplicates has been found in POSTADR column:
Fiat, Punto, 500, P4
BMW, E64, SE0, P4
Here is separate method I use for email:
public static void CreateMailItem(string EmailBody)
{
//Outlook.MailItem mailItem = (Outlook.MailItem)
// this.Application.CreateItem(Outlook.OlItemType.olMailItem);
Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MailItem mailItem = app.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
//string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), #"Data\Robot.jpg");
//string[] files = File.ReadAllLines(path);
mailItem.Subject = "There was an error";
mailItem.To = "email#example.com";
//mailItem.Attachments.Add(files);
mailItem.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatHTML;
string msgHTMLBody = "<html><body>" +
EmailBody + "</body></html>";
mailItem.HTMLBody = msgHTMLBody;
mailItem.Importance = Microsoft.Office.Interop.Outlook.OlImportance.olImportanceHigh;
mailItem.Display(false);
mailItem.Send();
Environment.Exit(-1);
}
Here is full process that can be tested: https://dotnetfiddle.net/qEnpmj
It seems you want to show POSTADR value which is duplicate over multiple rows. You should Select(x => x.POSTADR) and apply Distinct() on that like below.
string combindedString = string.Join("\n", duplicatesPOSTADR.Select(x => x.POSTADR).Distinct());
Related
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
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
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 an OL addin ( c# com using addin express) that is doing something like this
mailItem = (Outlook.MailItem)OutlookApp.CreateItem(Outlook.OlItemType.olMailItem);
mailItem.To = ReceipientEmailAddress;
mailItem.Subject = "SOME TEXT";
mailItem.Body = NewBody;
mailItem.Display(false);
This is however causing the default signature to disappear
i am assuming this is because a newBody is being set
I am not able to read the signature in any way or cause the mail creation to include the signature
oh this is OL 2007 .NET 2.0
I had same problem and found no answer, so I decided to solve this by myself getting the signature manually, this is what I did.
private string ReadSignature()
{
string appDataDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Microsoft\\Signatures";
string signature = string.Empty;
DirectoryInfo diInfo = new DirectoryInfo(appDataDir);
if (diInfo.Exists)
{
FileInfo[] fiSignature = diInfo.GetFiles("*.htm");
if (fiSignature.Length > 0)
{
StreamReader sr = new StreamReader(fiSignature[0].FullName, Encoding.Default);
signature = sr.ReadToEnd();
if (!string.IsNullOrEmpty(signature))
{
string fileName = fiSignature[0].Name.Replace(fiSignature[0].Extension, string.Empty);
signature = signature.Replace(fileName + "_files/", appDataDir + "/" + fileName + "_files/");
}
}
}
return signature;
}
Hope this helps.
This one work for me without any additional code.
olMail = outlook.CreateItem(0);
olMail.To = toEmailID;
olMail.Subject = "Subject";
if (attachments != null)
{
foreach (var path in attachments)
{
olMail.Attachments.Add(path);
}
}
olMail.Display();
//Display email first and then write body text to get original email template and signature text.
if (string.IsNullOrWhiteSpace(htmlBody))
{
if (!string.IsNullOrWhiteSpace(body))
{
olMail.Body = body + olMail.Body;
}
}
else
{
olMail.HTMLBody = htmlBody + olMail.HTMLBody;
}
Hope this helps.