Email on predefined template via outlook C# - 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();
}

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

Best Way to implement Email generation in this scheduled console app

I have never programmatically generated and sent email notifications before. What I need to do is this, if this program fails to move files or encounters an exception to generate an email and (preferably) attach a Log.txt file to the email then send it. This app will be ran from an enterprise scheduler and ran 1/hour to manage the files and folders.
Here is the functional code that I currently have (no email implementation exists yet) I have commented in the locations that I would like to send an email
using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Runtime.InteropServices;
namespace FileOrganizer
{
class Program
{
//These are the folder to organize and delimeter that is in the filenames to split off a folder from
static string folder = ConfigurationManager.AppSettings["folder"]; //"C:\Users\MyUserName\Desktop\Organize Me"
static string delim = ConfigurationManager.AppSettings["delim"]; // delim = "__"
//location for the log.txt file
static string logPath = ConfigurationManager.AppSettings["logPath"]; //C:\Users\MyUserName\Desktop\Log.txt
//contact list from the app.config
static string emailTo = ConfigurationManager.AppSettings["notifyEmailAddress"]; //multiple email addresses delimited by a ; example = tom#domain.com;dick#differentDomain.com;harry#domain.com
//for the log.txt reporting
static int filesMoved = 0;
static int filesNOTmoved = 0;
static string fileNamesNOTmoved = "";
static int foldersCreated = 0;
static string message = "";
static string stackTrace = "";
//used for passing all the objects into the log method
static object[] details = new object[6];
static void Main(string[] args)
{
try
{
using (StreamWriter w = File.AppendText(logPath))
{
int total = organizeFolder(delim, folder);
details[0] = filesMoved;
details[1] = filesNOTmoved;
details[2] = fileNamesNOTmoved;
details[3] = foldersCreated;
details[4] = "No Errors Found";
details[5] = "No Errors Found";
Log(details, w);
if (filesNOTmoved > Convert.ToInt32(filesNOTmoved))
{
//generate email to notify of filesNames not moved (prefer to send Log.txt as attachment)
}
}
using (StreamReader r = File.OpenText(logPath))
{
DumpLog(r);
}
}
catch (Exception ex)
{
using (StreamWriter w = File.AppendText(logPath))
{
details[0] = filesMoved;
details[1] = filesNOTmoved;
details[2] = fileNamesNOTmoved;
details[3] = foldersCreated;
details[4] = ex.Message.ToString();
details[5] = ex.StackTrace.ToString();
Log(details, w);
}
//generate email to notify of Error and (prefer to send Log.txt as attachment)
using (StreamReader r = File.OpenText(logPath))
{
DumpLog(r);
}
}
}
/*Takes a folder and organizes it into folder by naming folder whatever
* is in front of the delimeter Example -->(folderName__fileName.txt would be moved
* to a new or existing folder named folderName. Final path for file would
* look like this folderName\folderName__fileName.txt)
*
* It will not move file if it already exists in the new location, instead
* it prompts user that they should rename file and run program again.*/
static int organizeFolder(string delimeter, string rootPath)
{
//counter for total files in Folder
int Count = 0;
int totalMoved = 0;
FileInfo[] fileNames;
DirectoryInfo di = new DirectoryInfo(rootPath);
//set all file names as a string from network directory into an array
fileNames = di.GetFiles("*.*");
Count = fileNames.Length;
//Count = 0;//just to test exception handling
//if no files exist in network folder throw error message.
if (Count == 0)
{
fileNamesNOTmoved = "No Files Were In Directory to Move.";
}
else //files exist in network folder
{
int delimIndex = 0;
string folderName;
for (int i = 0; i < Count; i++)
{
if (fileNames[i].ToString().Contains(delimeter))
{
delimIndex = fileNames[i].ToString().IndexOf(delimeter);
folderName = fileNames[i].ToString().Substring(0, delimIndex);
//if folder doesnt exist create it here.
folderCreation(rootPath, folderName);
if (!File.Exists(rootPath + #"\" + folderName + #"\" + fileNames[i].Name))
{
File.Move(rootPath + #"\" + fileNames[i].ToString(), rootPath + #"\" + folderName + #"\" + fileNames[i].Name);
filesMoved++;
}
else
{
if (fileNamesNOTmoved == "")
fileNamesNOTmoved += "| ";
fileNamesNOTmoved += fileNames[i].Name + " | ";
filesNOTmoved++;
}
totalMoved++;
}
}
}
return totalMoved;
}
//if folder does not exist this method will create it
private static void folderCreation(string strTempPath, string folderName)
{
strTempPath = strTempPath + #"\" + folderName;
if (!Directory.Exists(strTempPath))
{
//Create \folderName
Directory.CreateDirectory(strTempPath);
foldersCreated++;
}
}
//adds entries to the log.txt file
public static void Log(object[] details, TextWriter w)
{
w.Write("\r\nLog Entry : ");
w.WriteLine("{0} {1}", DateTime.Now.ToShortTimeString(), DateTime.Now.ToShortDateString());
w.WriteLine(" :");
w.WriteLine(" :{0}", "Files Moved = " + details[0].ToString());
w.WriteLine(" :{0}", "Folders Created = " + details[3].ToString());
w.WriteLine(" :{0}", "Files Not Moved = " + details[1].ToString());
w.WriteLine(" :{0}", "Files Names Not Moved = {" + details[2].ToString() + "}");
w.WriteLine(" :{0}", "Error Message = " + details[4].ToString());
w.WriteLine(" :{0}", "Error Stack Trace = " + details[5].ToString());
w.WriteLine("---------------------------------------------------------------------------------------");
}
public static void DumpLog(StreamReader r)
{
string line;
while ((line = r.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
}
Basically would like the email to say:
Subject: Data Management Error Notification
Body: This is an Auto-Generated email to notify you there
was an error attempting to clean up the Files in the Directory.
Please refer to Attached Log.txt File for more detailed information.
Attachment: Log.txt
As it turns out SMTP was the way to go and Due to restrictions on my local machine I could only access it from the Dev, Qua, & Prd Servers. Once tested as admin from any of those locations.. email sent perfectly!!!
using the App.Config to hold all my To's, Froms, and the SMTP Host info and passing HTML as a string object into the method, here is the method I used to send email.
public static void sendMail(string msg)
{
SmtpClient smtpClient = new SmtpClient();
MailMessage message = new MailMessage();
MailAddress fromAddress = new MailAddress(emailFrom);
smtpClient.Host = smtpHost;
message.From = fromAddress;
message.Subject = "Test Email";
message.IsBodyHtml = true;
message.Body = msg;
message.To.Add(emailTo);
message.Priority = MailPriority.High;
smtpClient.Send(message);
}

Embedding picture to outlook email body

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

how to attach the file using telerik Rad Async Upload to a mail

Please tell me hoe to attach the file using telerik rad upload in a mail and send the mail.
I tried differrent scenarios to attach the file to the mail but it doesn't get attached.
Here is the scenario: I used target folder to save it on the webserver and attach the file from that location.
if (rdtxtAdditionalEmail.Text != "")
{
char[] delimiterChars = { ';' };
string text = rdtxtAdditionalEmail.Text;
string[] words = text.Split(delimiterChars);
foreach (string s in words)
{
newEmail.To = dr["Email"].ToString();
newEmail.From = "sy#mydomain.com";
newEmail.Subject = rdtxtSubject.Text;
newEmail.BodyFormat = MailFormat.Html;
newEmail.Body = rdtxtSubject.Text;
List<EmailAttachment> attachments = new List<EmailAttachment>();
foreach (EmailAttachment attach in attachments)
{
System.Net.Mail.Attachment attachFile = new Attachment("C:/Inetpub /wwwroot/DotNetNuke/Data/" + attach.fileName);
newEmail.Attachments.Add(attachFile);
}
for (int i = 0; i < rdauAttachments.UploadedFiles.Count; i++)
{
UploadedFile file = rdauAttachments.UploadedFiles[i];
EmailAttachment attachment = new EmailAttachment();
attachment.filePath = "C:/Inetpub/wwwroot/DotNetNuke/Data/" + rdauAttachments.UploadedFiles[i].GetName();
attachment.fileName = rdauAttachments.UploadedFiles[i].GetName();
newEmail.Attachments.Add(attachment);
}
SmtpMail.Send(newEmail);
}
}
I also try to do it using the demo exapmle in telerik pages but it didnot workout.
Please help me.
Thanks,
Sravanthi
string filename = string.Empty;
string path = string.Empty;
MailMessage mailMsg = new MailMessage();
if (AsyncUpload1.UploadedFiles.Count > 0)
{
foreach (UploadedFile file in AsyncUpload1.UploadedFiles)
{
filename = file.FileName;
path = System.IO.Path.GetFileName(filename);
string Withoutext = System.IO.Path.GetFileNameWithoutExtension(filename);
file.SaveAs(Server.MapPath("~/AttachMents/") + path);
FileStream fs = new FileStream(Server.MapPath("~/AttachMents/") + filename,
FileMode.Open, FileAccess.Read);
System.Net.Mail.Attachment a = new System.Net.Mail.Attachment(fs, filename,
MediaTypeNames.Application.Octet);
mailMsg.Attachments.Add(a);
}
}

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