Embedding picture to outlook email body - c#

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

Related

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

Getting exact File Path with File Upload to send file via Email C# ASP.NET

I want to send a file via email using c# ASP.net (Maybe more files too, but for the moment I'm concerned about sending at least only one file)
For the moment, I do have a method that does work if you want to send an Email
public string EnviarMensaje(int intIdVendedor, string strCorreoPara, string strCorreosAdicionales, string strTema, string strMensaje, string strRuta)
{
string strResultado="";
DataTable dt = ConexionBD.GetInstanciaConexionBD().GetVendedorEspecifico(intIdVendedor);
string strCuerpo = strMensaje + "\n\n\n\nMensaje Enviado Por:\n" + dt.Rows[0]["Vendedor"] + "\n" + dt.Rows[0]["Email"] + "\n" + dt.Rows[0]["Telefono"];
string[] strListaCorreos = strCorreosAdicionales.Split(new Char[] {' ', ','}, StringSplitOptions.RemoveEmptyEntries);
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtpout.secureserver.net");
mail.Subject = strTema;
mail.Body = strCuerpo;
mail.From = new MailAddress(strCorreoDe);
mail.To.Add(strCorreoPara);
foreach (string c in strListaCorreos)
{
mail.To.Add(c);
}
if (strRuta != "")
{
Attachment attachment;
attachment = new Attachment(strRuta);
mail.Attachments.Add(attachment);
}
SmtpServer.Port = 80;
SmtpServer.Credentials = new System.Net.NetworkCredential(strCorreoDe, strContrasena);
SmtpServer.EnableSsl = false;
SmtpServer.Send(mail);
strResultado = "Exito";
}
catch (Exception ex)
{
strResultado = ex.ToString();
}
return strResultado;
}
in aspx I have
<asp:FileUpload ID="fileUploadArchivos" runat="server" />
<asp:ImageButton ID="imgBtnEnviar" runat="server" Height="60px" Width="60px" ImageUrl="~/img/iconos/email.png" CausesValidation = "True" ValidationGroup="vgpCorreo" onclick="imgBtnEnviar_Click" />
and on the cs I have
EnviarEmail objEmail = new EnviarEmail();
protected void imgBtnEnviar_Click(object sender, ImageClickEventArgs e)
{
if (fileUploadArchivos.HasFile)
{
strArchivo = Path.GetTempFileName();\\RIGHT NOW I LEFT IT THIS WAY, BUT I NOW THAT HERE IS THE PROBLEM, I DON'T KNOW WHTAT CAN I DO HERE
}
string strResultado = objEmail.EnviarMensaje((int)Session["IdVendedor"], lblCorreoPara.Text, tbxCorreoPara.Text, tbxTema.Text, tbxMensaje.Text, strArchivo);
}
However, the problem is in a FileUpload.
I have tried many methods like, Server.MapPath, Path.GetFileName, GetDirectoryName, GetFullPath, GetPathRoot... and I'm always getting either nothing, only the filename or a completely different path (I guess is a server kind of path)..
I only for the moment want to get a file path as simple as C:\Test.txt for example...
I suppose that if I can get that exact string from the FileUpload, I'll be able to send it... However, I can't figure out how to make it work.
Hope you can help me
Thanks
If you need a local copy of the file uploaded kept on the server you can just do
fuFileUpload.SaveAs(MapPath(filepath));
Then your strRuta can use the file you just saved via
strRuta = Server.MapPath(filepath);
ready to pass into the new Attachment object.
You don't need to save the file at all to disk, not if all you want to do with it is add it as an attachment.
FileUpload has a FileContent property that is a Stream - some of the constructors of the Attachment class take a stream as a parameter.
The solution is to pass this stream to your method and use it directly.
In code behind:
string strResultado = objEmail.EnviarMensaje((int)Session["IdVendedor"],
lblCorreoPara.Text,
tbxCorreoPara.Text,
tbxTema.Text,
tbxMensaje.Text,
fileUploadArchivos.FileContent);
In your class:
public string EnviarMensaje(int intIdVendedor,
string strCorreoPara,
string strCorreosAdicionales,
string strTema,
string strMensaje,
Stream attachmentData)
{
...
var attachment = new Attachment(attachmentData, "nameOfAttachment");
...
}
You can try with this, using a stream instead of a simple text:
public string EnviarMensaje(int intIdVendedor, string strCorreoPara, string strCorreosAdicionales, string strTema, string strMensaje, string strRuta)
{
string strResultado="";
DataTable dt = ConexionBD.GetInstanciaConexionBD().GetVendedorEspecifico(intIdVendedor);
string strCuerpo = strMensaje + "\n\n\n\nMensaje Enviado Por:\n" + dt.Rows[0]["Vendedor"] + "\n" + dt.Rows[0]["Email"] + "\n" + dt.Rows[0]["Telefono"];
string[] strListaCorreos = strCorreosAdicionales.Split(new Char[] {' ', ','}, StringSplitOptions.RemoveEmptyEntries);
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtpout.secureserver.net");
mail.Subject = strTema;
mail.Body = strCuerpo;
mail.From = new MailAddress(strCorreoDe);
mail.To.Add(strCorreoPara);
foreach (string c in strListaCorreos)
{
mail.To.Add(c);
}
bool hasAttachment = !string.IsNullOrWhitespace(strRuta);
System.IO.FileStream stream = null;
Attachment attachment = null;
if (hasAttachment)
{
// Create a file stream.
stream = new FileStream(strRuta, FileMode.Open, FileAccess.Read);
// Define content type.
ContentType contentType = new ContentType();
contentType.MediaType = MediaTypeNames.Text.Plain; // or whatever your attachment is
// Create the attachment and add it.
attachment = new Attachment(stream, contentType);
mail.Attachments.Add(attachment);
}
SmtpServer.Port = 80;
SmtpServer.Credentials = new System.Net.NetworkCredential(strCorreoDe, strContrasena);
SmtpServer.EnableSsl = false;
SmtpServer.Send(mail);
strResultado = "Exito";
// Don't forget to release the resources if the attachment has been added
if (hasAttachment)
{
data.Dispose();
stream.Close();
stream.Dispose();
}
}
catch (Exception ex)
{
strResultado = ex.ToString();
}
return strResultado;
}

Email on predefined template via outlook C#

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

how to send mail , using outlook - right to left text in the message?

i send mail like this:
string sampleDisplayName = "Me";
Microsoft.Office.Interop.Outlook.Application sampleApp = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MailItem sampleMessage = (Microsoft.Office.Interop.Outlook.MailItem)sampleApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
sampleMessage.To = "Me#Gmail.com";
sampleMessage.Subject = "My subject";
LosMSG = "My message here";
LosMSG += "\n------------";
LosMSG += "\nand here";
sampleMessage.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatRichText;
sampleMessage.Body = LosMSG;
sampleMessage.BCC = ToHoSend;
int samplePosition = (int)sampleMessage.Body.Length + 1;
int sampleType = (int)Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue;
sampleMessage.Display(true);
sampleMessage = null;
sampleApp = null;
but the message is left-to-right
how i do it right-to-left ?
thank's in advance
I believe the Outlook automation object model doesn't include support for RTL: if you make your message format HTML, though, you can include the CSS direction:rtl;

How do I append a User Mail signature in Outlook to an email created programmatically

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.

Categories