I'm working on a Selenium test which generates a report and then sends the report to an email address when it's finished. The script works flawlessly up until I have to send the email report.
The weird thing is that if I run the script from inside Visual Studio, the email sends fine, but when I build the solution and then set the script to run automatically from the task schedule it fails. The rest of the script runs fine, the report gets generated, it just doesnt send the email.
I'm not a Visual Studio expert, so I'm thinking it may possibly be something in my settings.
Here's the code to send the email using Outlook:
Outlook.Application oApp = new Outlook.Application();
Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
oMsg.HTMLBody = "Please find the attached Contract Remaining Hours report for the week of " + DateTime.Today.ToString("D");
String sDisplayName = fileName;
int iPosition = (int)oMsg.Body.Length + 1;
int iAttachType = (int)Outlook.OlAttachmentType.olByValue;
Outlook.Attachment oAttach = oMsg.Attachments.Add
(pathToFile + fileName, iAttachType, iPosition, sDisplayName);
oMsg.Subject = "Contract Remaining Hours Report " + DateTime.Today.ToString("D");
Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add("tom.depiera#tbs.toshiba.com");
oRecip.Resolve();
oMsg.Send();
Related
So, this may be a silly question (or something that's impossible), but I just wanted to ask in case anyone knows something. I'm trying to open Outlook (either through Office 365- Browser or through the Outlook Desktop Application) to compose an email. I got that working fine. What I want to know is, if there's a way that I can capture what was composed (like, Body, To, Subject, Attachments) in my WPF application so that I can update it on my end. Do you guys think if this is possible?
Here's the sample code I have: (For opening this in the browser)
string To = "abc#ftr.com";
string subject = "Test Email";
string body = "This is a test email, Please ignore";
string url = #"https://outlook.office.com/?path=/mail/action/compose&to=" + To + "&subject=" + subject + "&body=" + body;
System.Diagnostics.Process.Start(url);
And here's the code for opening it in Outlook Desktop App:
Microsoft.Office.Interop.Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MailItem oMsg = (Microsoft.Office.Interop.Outlook.MailItem)oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
oMsg.Subject = "subject something";
oMsg.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatHTML;
oMsg.HTMLBody = "Test Email";
oMsg.Attachments.Add("c:/temp/test.txt", Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing);
oMsg.Display(true);
Thank you!
You can hook the ItemSend event, which will give you a reference to the MailItem object that is about to be send. Here is some sample code I copied from the Microsoft Community Forums
public void SendEnMail(Office.IRibbonControl control) //OnAction Function
{
Outlook.Application oApp = new Outlook.Application();
Outlook._MailItem myMail = (Outlook._MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
myMail.Display(true);
Outlook.Application application = Globals.ThisAddIn.Application;
application.ItemSend += new Outlook.ApplicationEvents_11_ItemSendEventHandler(Application_ItemSend);
}
void Application_ItemSend(object Item, ref bool Cancel)
{
string a = ((Microsoft.Office.Interop.Outlook.MailItem)Item).Body;
System.Windows.Forms.MessageBox.Show(a);
Cancel = true;
}
I am trying to save last send mail from Outlook to my desktop as .msg format.
But i am getting error with my code in last line of my code as follow:
((Microsoft.Office.Interop.Outlook.MailItem)mail).SaveAs(mydesktop+ "\\Myapplication\\" + subject.Replace(":", "").Replace("/", "").Replace("|", "") + ".msg", Microsoft.Office.Interop.Outlook.OlSaveAsType.olMSG);
Error:System.Runtime.InteropServices.COMException: 'The item has been moved or deleted.'
string mailto = labelControl53.Text + ";" + labelControl56.Text ;
string cc = "myaccount#mymail.com";
string subject= labelControl7.Text + "-" + comboBoxEdit1.Text + "-" + textEdit6.Text + " Yüklemesi hk.";
string mydesktop= Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
Microsoft.Office.Interop.Outlook.Application mailat = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MailItem mail = (Microsoft.Office.Interop.Outlook.MailItem)mailat.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
mail.To = mailto;
mail.CC = cc;
mail.Subject = subject;
mail.Importance = Microsoft.Office.Interop.Outlook.OlImportance.olImportanceHigh;
mail.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatHTML;
mail.HTMLBody = getHTMLupload();
((Microsoft.Office.Interop.Outlook.MailItem)mail).Send();
((Microsoft.Office.Interop.Outlook.MailItem)mail).SaveAs(mydesktop+ "\\Myapplication\\" + subject.Replace(":", "").Replace("/", "").Replace("|", "") + ".msg", Microsoft.Office.Interop.Outlook.OlSaveAsType.olMSG);
System.Runtime.InteropServices.COMException: 'The item has been moved or deleted.'
This mail object is released after send so you don't have access to it.
You probably have to add an event handler. Something like this might work.
((Outlook.ItemEvents_10_Event)mail).Send += new Microsoft.Office.Interop.Outlook.ItemEvents_10_SendEventHandler(SaveSentMail);
static void SaveSentMail(ref bool Cancel)
{
mail.SaveAs(mydesktop+ ....);
}
If you want to save the last sent item in Outlook you need to handle the ItemAdd event of the Items class which comes from the Sent Items folder. Typically mail items are placed into the Sent Items folder as soon as they are sent. However, users or other add-ins may set the DeleteAfterSubmit property which sets a Boolean value that is True if a copy of the mail message is not saved upon being sent, and False if a copy is saved in Sent Items folder.
Or just call the SaveAs before submitting items in Outlook (before the Send method).
I have a console application that sends emails to several (12 currently) different email groups. The process loops through and each time creates a different excel workbook, saves the workbook, then sends an email with this workbook attached.
This process ran great for several months. Now, the program will make it through 2 emails, then it will throw an exception for Failure sending mail. I have found the inner exception is Unable to read data from the transport connection: net_io_connectionclosed
The workbooks are created via 2 SQL stored procs. Even when the email fails, the workbooks are created and can be opened so I don't think it has anything to do with the SQL involved.
I have seen several other SO issues for similar issues, but since my process works for 2, fails for 1, works for 2, fails for 1.... I believe my issue is different than a simple port or credentials issue.
Here is the code I have before loop to declare the SmtpClient
SmtpClient client = new SmtpClient("intmail.MyDomain.net", 25);
NetworkCredential cred = new NetworkCredential("myEmailAddress#email.com", "");
client.Credentials = cred; // Send our account login details to the client.
client.EnableSsl = false; // Read below.
Here is my code inside the loop for creating email, attaching workbook, and sending.
MailMessage msg = new MailMessage();
Attachment xls01 = new Attachment(filePath);
string emailTo = ClientEmail;
string[] emailTos = emailTo.Split(new char[] { ';' });
foreach (string To in emailTos)
{
msg.To.Add(To);
Console.WriteLine(To);
}
msg.From = new MailAddress("myEmailAddress#email.com");
//msg.CC.Add(new MailAddress("myEmailAddress#email.com"));
msg.Subject = ClientName + reportMonth + " " + reportYear;
msg.Body = "Attached is report for period ending on the last day of " + reportMonth + " " + reportYear + ".\r\nAlso attached are the 13 month trends.";
msg.Attachments.Add(xls01);
try
{
client.Send(msg);
}
catch (Exception ex)
{
Console.WriteLine(ex); //Should print stacktrace + details of inner exception
if (ex.InnerException != null)
{
Console.WriteLine("InnerException is: {0}", ex.InnerException);
}
}
Most likely you are hitting smtp server antispam filter when you sending messages one right after another. Try to space them apart in time and make 3 attempts for each send. Obviously you should not stop if any one send is failed, you should go through all 12.
I am looking to generate an Outlook message from within my program, I am able to build and send from within the program or build and save, what I would like is to build then display to allow the user to manually select recipients from the AD listings... The code below is a mixup of samples here and other tutorial sites however none I can find just build then "display" the email without saving a draft or sending it from within the program...
also I am looking to find a way i can create a UNC link inside of an email IE: write out a path to the users folder \\unc\path\%USERNAME% or the likes
private void sendEmailOutlook(string savedLocation, string packageName)
{
try
{
Microsoft.Office.Interop.Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MailItem oMsg = (Microsoft.Office.Interop.Outlook.MailItem)oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
oMsg.HTMLBody = "Attached is the required setup files for your <i><b>soemthing</i></b> deployment package.";
oMsg.HTMLBody += "\nPlease save this file to your network user folder located.<br /><br/>\\\\UNC\\data\\users\\%USER%\\";
oMsg.HTMLBody += "\nOnce saved please boot your Virtual machine, locate and execute the file at <br /> <br />\\\\UNC\\users\\%USER%\\";
int pos = (int)oMsg.Body.Length +1;
int attachType = (int)Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue;
Microsoft.Office.Interop.Outlook.Attachment oAttach = oMsg.Attachments.Add(savedLocation, attachType, pos, packageName);
oMsg.Subject = "something deployment package instructions";
oMsg.Save();
}
catch(Exception ex)
{
Console.WriteLine("Email Failed", ex.Message);
}
Microsoft.Office.Interop.Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MailItem oMsg = (Microsoft.Office.Interop.Outlook.MailItem)oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
oMsg.Subject = "something deployment package instructions";
oMsg.BodyFormat = OlBodyFormat.olFormatHTML;
oMsg.HTMLBody = //Here comes your body;
oMsg.Display(false); //In order to display it in modal inspector change the argument to true
Regarding the link to the folder you should be able to use(in case that you know User Name):
Link
A lot of companies have their employees user names attached to address entries (looks something like "John Doe(Jdoe)" where Jdoe is a username).
when your user select a recipients or tries to send the email you could catch those event, and do something like
foreach (Outlook.Recipient r in oMsg.Recipients)
{
string username = getUserName(r.Name);// or r.AddressEntry.Name instead of r.Name
oMsg.HTMLBody += "<a href='C:\\Users\\" + username + "'>Link</a>"
}
oMsg.Save();
oMsg.Send();
where getUserName() is a method that extracts only the userName (Could use substring or RegEx).
Make sure that mail's body is a valid HTML
/n won't give you a new line you should use <br> insted.
I have a WinForms app that at the click of a button automatically produces an Outlook mail as follows:
public static void CreateOutlookEmail(string pFileName, string pCaseFolder, string pEmail, string pSubject, string pMessage)
{
try
{
Outlook.Application outlookApp = new Outlook.Application();
Outlook.MailItem mailItem = (Outlook.MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem);
mailItem.Subject = pSubject;
mailItem.To = pEmail;
mailItem.Body = pMessage;
mailItem.Importance = Outlook.OlImportance.olImportanceNormal;
mailItem.Display(false);
string fileDetails = pCaseFolder + "\\" + pFileName + #".eml";
mailItem.SaveAs(fileDetails);
}
catch (Exception eX)
{
throw new Exception("cDocument: Error occurred trying to Create an Outlook Email"
+ Environment.NewLine + eX.Message);
}
}
The code succesfully opens a new Outlook email, and populates it with the details sent into the method e.g. email address, subject and the body of the message.
Also when I locate the folder (sent in as a paramater) I can see the email document has been saved.
The issue is, that when I open the email from the folder, the email document is totaly blank ii.e. no email address, subject or message.
What am I doing wrong?
Your code is fine. Just use extension ".msg" instead of ".eml". Also the eml format does not exist under Outlook.OlSaveAsType