I use a very simple code to generate emails using outlook in my c# application. It works fine when Outlook is already opened.(Even though it asks for permission to open the email.But after I grant access a new Outlook message window opens with the generated email). But the real problem is if Outlook is not opened the application crashes at the line
Microsoft.Office.Interop.Outlook.Recipient oTORecipt = oMsg.Recipients.Add(email);
ERROR:An exception (first chance) of type 'System.Runtime.InteropServices.COMException' occurred in Birthday_Mailing.dll.
Additional information: discontinued operation (Exception from HRESULT: 0x80004004 (E_ABORT))
If a handler is available for this exception, the program may continue to run safely.
And my whole code can be seen as below
public void SendMail(string email, string name)
{
//// Create the Outlook application by using inline initialization.
Microsoft.Office.Interop.Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.Application();
////Create the new message by using the simplest approach.
Microsoft.Office.Interop.Outlook.MailItem oMsg = (Microsoft.Office.Interop.Outlook.MailItem)oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
Microsoft.Office.Interop.Outlook.Recipient oTORecipt = oMsg.Recipients.Add(email); //oRecips.Add(t);
oTORecipt.Type = (int)Microsoft.Office.Interop.Outlook.OlMailRecipientType.olTo;
oTORecipt.Resolve();
oMsg.Subject = "Herzlichen Glückwunsch";
oMsg.HTMLBody = "<html>" +
"<head>" +
"<title>Happy Birthday</title>" +
"</head>" +
"<body style='background-color:#E6E6E6;'>" +SelectImage+
"<div style='font-family: Georgia, Arial; font-size:14px; '>Liebe/r " + " " +
name + ",<br /><br />" +
"alles Gute zum <b>Geburtstag!</b> Wir wünschen einen schönen Tag und für das kommende Jahr Gesundheit, Glück und Erfolg." +
"<br /><br /><br /><br /><br />" +
"Mit den besten Grüßen,<br />" +
"XXYYZZ" +
"</div>" +
"</body>" +
"</html>";
oMsg.Save();
oMsg.Display();
oMsg = null;
oApp = null;
I'm not an expert in coding. Can someone help me to find where the actual problem is? Thanks in advance!
Microsoft.Office.Interop.Outlook.Inspector oInspector = oMsg.GetInspector;
I added this one line after declaring oMsg Object which solved the problem. But still before the message window opens Outlook asks for the users permission to display the email.
***Yet I wouldn't mark this as the Answer because it's not the best solution you can give for this question.
UPDATE: I found out that the above mentioned issue was due to some security system in our server. This is the correct answer. Thanks to #MikeMiller for showing the correct path
Related
I'm trying to create a function for an application to automatically copy over specific files during the final stage of a job. The only issue here is that the copy location is a protected share drive and uses a separate login instead of being validated by the active directory so I've got to do a bit of a workaround to get File.Copy() working. My workaround has been to call the built in net.exe utility and passing a command line argument that points to the share drive to open up a connection to the drive then using File.Copy() to get the file where it needs to go then deleting the connection. The issue at hand is that this works great on my computer but when anyone else on the team runs the same program a "Logon failure: unknown user name or bad password" is thrown. I'm at a bit of loss as to why this would happen since the username and password are static and not being changed and everyone on the team has the same network permissions I do. Here is the WPF/C# code I'm using to do this:
try
{
string mrdfDropPath = #"dropPathHere";
string MRDFPath = #"storePath\test.xml";
string command = #"use " + mrdfDropPath + #" /user:CORP\Username Password";
Process.Start("net.exe", command);
File.Copy(MRDFPath, mrdfDropPath + "test.xml");
string command2 = #"use " + mrdfDropPath + #" /delete";
Process.Start("net.exe", command2);
StreamWriter writer = new StreamWriter(#"logPath\log.txt", true);
writer.WriteLine(mrdfDropPath + "test.xml" + "," + File.GetLastWriteTime(MRDFPath).ToString());
writer.Close();
}
catch (Exception e)
{
StreamWriter writer = new StreamWriter(#"logPath\log.txt", true);
writer.WriteLine(e.Message);
writer.Close();
}
Like I said this works as expected during debug and when I run the application, but for anyone else it is throwing the error.
mailItem.HTMLBody = "Dear IT Dept. You have received a new "+ comboBox3.Text + " priority task to complete from " + textBox1.Text + ". Please save the attached file and fit the task in to your schedule. Once completed please contact the " + textBox2.Text + " for comfirmation the task is completed to thier expectations. The Task is as follows: " + richTextBox1.Text + " Kind Regards, " + textBox1.Text + "";
I basically want to highlight the text/combo boxes or at least change their font color. Annoyingly you can't see the html code I used but it should be pretty obvious but I tried using the font color...with no luck. can't see where I'm going wrong
I can see that you try to put value of textBox2.txt. Your mistake is that wrote textBox2.txt as a string content. So you can achive this with using string.Format method.
You should to change it with this:
mailItem.HTMLBody = string.Format("<html><body><p>Dear IT Dept.</p> <p>You have received a new task to complete from ({0}) Please check the attached file and fit the task in to your schedule.</p><p> Once completed please contact the provided contactee for comfirmation the task is completed to thier expectations.</p>", textBox2.Text);
Notice that textBox2.Text and {0} element.
Note: You also wrong with syntax of TextBox.Text property.
You need to have:
mailItem.HTMLBody = "<html><body>... from " + textBox2.Text + " Please ...";
instead of
mailItem.HTMLBody = "<html><body>... from (textBox2.txt) Please ...";
There is no HTMLBody property on the MailMessage class (assuming this is what you're using?).
It's just Body.
You would do something like this:
mailItem.Body = string.Format("<html><body><p>Dear {0}.</p>", comboBox3.Text);
Etc...
var mailItem= new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp server addess");
mailItem.From = new MailAddress("your_email_address#xyz.com");
mailItem.To.Add("it-department#???.co.uk");
mailItem.Subject = string.Format("You have a new task from {0}", comboBox3.Text);
mailItem.To = "";
mailItem.Body =string.Format("<html><body><p>Dear IT Dept.</p> <p>You have received a new task to complete from {0} Please check the attached file and fit the task in to your schedule.</p><p> Once completed please contact the provided contactee for comfirmation the task is completed to their expectations.</p>",textBox2.txt);
attachment = new System.Net.Mail.Attachment(#"\\??-filesvr\shares\Shared\+++++Web Projects+++++\????\IssueReport.txt");
mailItem.Attachments.Add(#"\\??-filesvr\shares\Shared\+++++Web Projects+++++\??\IssueReport.txt");
mailItem.IsBodyHtml = true;
// Optional Items based on your smtp server.
/* SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
SmtpServer.EnableSsl = true;*/
SmtpServer.Send(mailItem);
MessageBox.Show("mail Send");
Did you mean :
mailItem.HTMLBody = "<html><body><p>Dear IT Dept.</p> <p>You have received a new task to complete from " + textBox2.Text + " Please check the attached file and fit the task in to your schedule.</p><p> Once completed please contact the provided contactee for comfirmation the task is completed to thier expectations.</p>";
?
In your version, "textbox2.txt" will be manipulated as a string, it won't be "parsed".
In mine it's a control on your form and we put its text content in the mail.
Edit : you asked how to emphase the variable, here is a example :
Try something like
mailItem.HTMLBody = "<html><body><p>Dear IT Dept.</p> <p>You have received a new task to complete from <strong>" + textBox2.Text + "</strong> Please check the attached file and fit the task in to your schedule.</p><p> Once completed please contact the provided contactee for comfirmation the task is completed to thier expectations.</p>";
The "strong" tag around your variable will put the name in bold.
I have a console app written in C# that uses MS Fax (FAXCOMEXLib) to send faxes. If I run the application manually or from a command prompt it works as expected. If I schedule the application with Task Scheduler or try to run from a service with a timer, it fails when calling the ConnectedSubmit2 on the FaxDocument object. The application runs as expected, gets the data, creates the pdf, connects to Fax Service, fills the FaxDocument properties, but bombs on ConnectedSubmit2. It feels like a security issue. The windows account the TaskScheduler runs under belongs to the administrator group.
This same application has worked on another Server 2008 (not R2) computer without issue with Task Scheduler.
The server in question is running Microsoft Server 2008 R2.
Recap: The application will work if run manually, fails if run from another process like Task Scheduler.
Any suggestions would be most appreciated. Thank you.
C# Code:
FAXCOMEXLib.FaxServer faxServer = new FAXCOMEXLib.FaxServer();
FAXCOMEXLib.FaxDocument faxDocument = new FAXCOMEXLib.FaxDocument();
ArrayList al = new ArrayList();
al.Add(orderPdfFilePath);
if (facesheetPdfFilePath != "")
al.Add(facesheetPdfFilePath);
if (write) Console.WriteLine("Preparing to Connect to Fax Server...");
sbLog.Append("Preparing to Connect to Fax Server...\r\n");
faxServer.Connect("");
if (write) Console.WriteLine("Connected.");
sbLog.Append("Connected.\r\n");
// Add Sender Information to outgoing fax
faxDocument.Sender.Name = dr2["FacilityName"].ToString();
faxDocument.Sender.Department = dr2["TSID"].ToString();
faxDocument.Sender.TSID = Truncate(dr2["TSID"].ToString(), 20);
faxDocument.Recipients.Add(dr2["FaxNumber"].ToString(), dr2["Pharmacy"].ToString());
faxDocument.Bodies = al.ToArray(typeof(string));
faxDocument.Subject = order;
if (write) Console.WriteLine("Attempting submit to fax server...");
sbLog.Append("Attempting submit to fax server...\r\n");
// attempt send...
try
{
object o;
faxDocument.ConnectedSubmit2(faxServer, out o);
if (write) Console.WriteLine("Fax sent successfully " + DateTime.Now.ToString());
sbLog.Append("Fax sent successfully " + DateTime.Now.ToString() + ".\r\n");
}
catch (Exception ex)
{
if (write) Console.WriteLine("SEND FAILED! " + order + " " + DateTime.Now.ToString() + " " + ex.Message);
sbLog.Append("SEND FAILED! " + order + " " + DateTime.Now.ToString() + ".\r\n" + ex.Message + "\r\n" + ex.InnerException + "\r\n");
error = true;
}
Errors in Event Log:
System.Runtime.InteropServices.COMException (0x80070102): Operation failed.
at FAXCOMEXLib.FaxDocumentClass.ConnectedSubmit2(IFaxServer pFaxServer, Object& pvFaxOutgoingJobIDs)
System.UnauthorizedAccessException: Access denied. at FAXCOMEXLib.FaxDocumentClass.ConnectedSubmit2(IFaxServer pFaxServer, Object& pvFaxOutgoingJobIDs) at ElementsTransmission.Program.Main(String[] args)
See
http://blogs.msdn.com/b/dougste/archive/2011/08/30/system-runtime-interopservices-comexception-0x80070102-operation-failed-trying-to-send-a-fax-from-and-asp-net-application.aspx
Bill
I have an ASP.NET application on my local machine that works. This application takes an SVG file and creates a PNG from it using inkscape. I have tried to migrate that application to my production server. Oddly, the png creation is not working. The really strange part is, an Exception is not being thrown either. I have taken the command line parameters that are being created and copied and pasted them into the command line environment and they work. For instance, here is the line:
inkscape.exe -f "C:\inetpub\wwwroot\MyTest\sample.svg" -e "C:\inetpub\wwwroot\MyTest\sample.png"
I thought it was something simple, so I extracted the code into a sample web project. This project just converts a .svg to a .png. Once again, it worked in my local environment, but not in the production environment. Here is the code:
protected void executeButton_Click(object sender, EventArgs e)
{
try
{
string sourceFile = Server.MapPath("svg") + "\\" + ConfigurationManager.AppSettings["sourceFile"];
string targetFile = Server.MapPath("png") + "\\" + ConfigurationManager.AppSettings["targetFile"];
string args = "-f \"" + sourceFile + "\" -e \"" + targetFile + "\" -w100 -h40";
string inkscape = ConfigurationManager.AppSettings["inkscapeExe"];
// Generate the png via inkscape
ProcessStartInfo inkscapeInfo = new ProcessStartInfo(inkscape, args);
Process inkscape = Process.Start(inkscapeInfo);
inkscape.WaitForExit(5000);
runLiteral.Text = "Success!<br />" + args;
}
catch (Exception ex)
{
runLiteral.Text = ex.GetType().FullName + "<br />" + ex.Message + "<br />" + ex.StackTrace;
}
}
Can someone tell me what I'm doing wrong?
Thank you!
A couple things to check:
Make sure that the application pool identity for the web application (found in IIS, usually NetworkService) has permissions to execute inkscape.exe
If that is fine, check to make sure that the directory grants Modify permissions to the apppool identity on the directory(ies) you are writing the PNG to ("C:\inetpub\wwwroot\MyTest")
Alternatively, you can use impersonation to run the executable under a specific Windows account.
How can I attach a file to this mailto string?
string mailto = "mailto:" + to + "&SUBJECT=" + subject + "?BODY=" + body +
"&Attachment=" + attachment;
This doesn't work; the file isn't attached.
Remove the quotes at the end of "attachment".
"mailto:" + to + "&SUBJECT=" + subject + "?BODY=" + body + "&Attachment=" + attachment
Where attachment has the attachment link.
Note: This will not work if the users dont have access to the attachment so you can try attaching and sending it through a c# code.
From what I saw on the web (and by trying it to), it is not always possible to do so. Some email client, and by some I mean lots of them, will not let you do this because it is considered a security hole. However, when it is accepted, the syntax provided by Shodan looks good.
Try this
var proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = string.Format("\"{0}\"", Process.GetProcessesByName("OUTLOOK")[0].Modules[0].FileName);
proc.StartInfo.Arguments = string.Format(" /c ipm.note /m {0} /a \"{1}\"", "someone#somewhere.com", #"c:\attachments\file.txt");
proc.Start();