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