"Send e-mail to" with Microsoft.Office.Interop.Outlook - c#

in my development machine I developed a method that work without problem. Its a simple button and when I clicked it open an outlook email with a email adress and some content But when I sent the code to the production enviroment... all users are getting an error on page_load of the page where the following method are set.
protected void btnSendEmail_Click(object sender, ImageClickEventArgs e)
{
//...
Microsoft.Office.Interop.Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook._MailItem oMailItem = (Microsoft.Office.Interop.Outlook._MailItem)oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
string name = someDataTable.Rows[0]["NAME"].ToString();
string url = HttpContext.Current.Request.Url.AbsoluteUri;
oMailItem.To = someEmail#Gmail.com;
oMailItem.Body = string.Format("hi {0}, \n \n [Insert the content mail here.] \n \n {1} ", name, url);
oMailItem.Subject = "Some Title";
oMailItem.Display(false);
}

The Microsoft Office Interop assemblies would open Outlook on the server (assuming Outlook is installed on the server), not on the client. Is that your intention?
The Microsoft Office Interop assemblies are not supported on the server side. See KB Article.
I suggest you switch to some other technology. If you're just trying to have the server send an email, try taking at look at the System.Net.Mail namespace. See How To Send An Email With C#.
If your intention is to launch an Outlook new email window on the client side, it's easy to accomplish that with a simple HTML anchor link. See Sending HTML in mailto anchor tag.

Related

Outlook Email won't display in web application

I have a web application with some functionality to allow a user to send an email using Microsoft.Office.Interop.Outlook.Application. I want to display the email to allow the user to add any text they may want before sending. It works as expected in localhost however in production it fails to display the email. My code is as follows:
OutlookApp outlookApp = new OutlookApp();
MailItem mailItem = outlookApp.CreateItem(OlItemType.olMailItem);
mailItem.To = address;
mailItem.Subject = subject;
mailItem.HTMLBody = body;
mailItem.Importance = OlImportance.olImportanceNormal;
mailItem.Display(false);
Outlook opens just fine when I use a Response.Redirect instead of the above.
Response.Redirect("mailto:" + email + "?subject=" + subject + "&body=" + body);
Any ideas/suggestions?
Create an EML (MIME) message with attachments etc. on the server and let the user download it. Outlook on the client side will be happy to open it. Don't forget to add the X-Unsent:1 MIME header to make sure the user can actually send it.

Generate Oulook Email From Server

I have an ASP.NET site that needs to be able to dynamically generate an email that will get sent back to the users local machine to then be sent via Outlook. The code below does just that but it uses the Outlook Interop to create the message and I was a bit hesitent to use Interop on a Web App. I looked into OpenXML but couldnt seem to find much on Outlook.
// Creates a new Outlook Application Instance
Microsoft.Office.Interop.Outlook.Application objOutlook = new Microsoft.Office.Interop.Outlook.Application();
// Creating a new Outlook Message from the Outlook Application Instance
Microsoft.Office.Interop.Outlook.MailItem mic = (Microsoft.Office.Interop.Outlook.MailItem)(objOutlook.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem));
mic.To = "to#email.com";
mic.CC = "cc#email.com";
mic.Subject = "Test Subject";
mic.HTMLBody = "Test Message Body";
string strNewEmailPath = strEmailPath + "\\EmailMessages\\" + strUser + "_Message_PEI.msg";
mic.SaveAs(strNewEmailPath, Microsoft.Office.Interop.Outlook.OlSaveAsType.olMSG);
HttpContext.Current.Response.ContentType = "application/vnd.ms-outlook";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=Message.msg");
HttpContext.Current.Response.TransmitFile(strNewEmailPath);
HttpContext.Current.Response.End();
Can anyone help with perhaps a better suggestion for automating an Outlook message using ASP.NET?
Update:
I did find the Javascript code which seems do have similar functionality.
var theApp //Reference to Outlook.Application
var theMailItem //Outlook.mailItem
//Attach Files to the email, Construct the Email including
//To(address),subject,body
var subject = sub
var msg = body
//Create a object of Outlook.Application
try
{
var theApp = new ActiveXObject("Outlook.Application")
var theMailItem = theApp.CreateItem(0) // value 0 = MailItem
//Bind the variables with the email
theMailItem.to = to
theMailItem.Subject = (subject);
theMailItem.Body = (msg);
//Show the mail before sending for review purpose
//You can directly use the theMailItem.send() function
//if you do not want to show the message.
theMailItem.display()
}
catch(err)
{
alert("Error");
}
I have had a similar need before. I shelved the idea because of the complexity of generating .msg files (though I think there's some commercial libraries that can do it). One alternative you may consider is installing an Outlook add-in on the user's machine. Poll the web server (or this would be a great case for SignalR so the server could push data) and have the web server send the details of the email to the user's machine. Then the add-in could generate the email based on the details it received from the server. This would avoid running Interop on the server (which is a bad idea). However, you'll now have the complexity of deploying an Outlook Add-In, but if this is a corporate environment it shouldn't be too difficult.
If you didn't want to do it as an add-in, you could still do it by just writing a service application that runs on the user's machine and uses Interop, but that still has all the complexities of the add-in technique.
Alternatively, if your email is really simple, you could just use a mailto URI. But I find them very limiting, since it's difficult or impossible to send an HTML message that way.
And lastly, you could have the server just send the email on the user's behalf, not involving code running on the user's machine at all.
I did find the Javascript code which seems do have similar functionality. I was hoping someone might have an OpenXML solution but this JS solution can work and is better than Outlook Interop
var theApp //Reference to Outlook.Application
var theMailItem //Outlook.mailItem
//Attach Files to the email, Construct the Email including
//To(address),subject,body
var subject = sub
var msg = body
//Create a object of Outlook.Application
try
{
var theApp = new ActiveXObject("Outlook.Application")
var theMailItem = theApp.CreateItem(0) // value 0 = MailItem
//Bind the variables with the email
theMailItem.to = to
theMailItem.Subject = (subject);
theMailItem.Body = (msg);
//Show the mail before sending for review purpose
//You can directly use the theMailItem.send() function
//if you do not want to show the message.
theMailItem.display()
}
catch(err)
{
alert("Error");
}

Gmail, Hotmail does not send images in mail content using imap or pop3

I am using HigLabo library to get inbox messages from Gmail (imap) or Hotmail (pop3).
My Code is similar to this for gmail;
ImapClient client = new ImapClient(ServerName);
client.UserName = UserName;
client.Password = Password;
client.Port = Port;
client.Ssl = Ssl;
MailMessage mailMessage = client.GetMessage(1);
Console.WriteLine(mailMessage.BodyText);
lets assume this message is a HTML mail coming from newegg. So BodyText property has whole content as html but img elements coming as [image: ] because gmail and hotmail does not send images to my application. to see images user has to go their real inbox and click on "show all images" (which is not the case for my client app)
I am wondering is it a solid rule from mail providers to not to send images coming from "untrusted source" or is there a workaround to get also images and show inbox mails to user properly?
I am not sure what's wrong with all other API's lastly I gave a shot to this library today;
limilabs mail.dll
and it is fetching mails exactly how it appears on browsers.

How to put contact us page in windows application c# [duplicate]

I'm thinking of implementing "Report a bug/Suggestions" option to my game, however I am not quite sure how I could get that working. I do not have my own server or anything, so I can't just send the text that user has written to there.
The only way I came up with is that the client would write a message and I would send it to an email account where I could read them. However, I do not want that users would need to send the reports through their personal accounts. I am not quite sure how I could implement this and googling didn't bring up any good suggestions.
I haven't done a lot of network stuff, so I'd really appreciate it if you could explain ( possibly even in code ) the process step-by-step.
I am using C# and the game is being programmed for Windows Phone 7.
Yes, it is absolutely possible to do that. From a relatively low-level perspective, you need to:
Resolve the MX (mail-exchanger) server for the e-mail account you want to send to.
Open a socket to the MX server.
Send the appropriate SMTP commands to cause the e-mail message to be delivered to your recipient account. You essentially have the freedom to set the "from" address to be any arbitrary thing you want.
SMTP is a very simple/human-friendly protocol, so it's not a massive effort to do all of that by hand. At the same time, there are prebuilt libraries that will handle all of that for you (except possibly the resolution of the recipient's MX server).
Note that emails sent this way are more likely to be filtered out as spam (generally because the sender's IP/hostname is not going to match whatever domain you put on the outgoing e-mail address you decide to use).
Also note that since you can set the "from" address to anything, you have the option of asking the user if they want to provide their actual contact address, and if they do you can make that the "from" address so that you can actually get back in touch with them if necessary.
You don't need to use email at all. Consider using an error reporting service like sentry or airbrake.
These services have clients that you embed in your program; which automatically log your errors, including any debugging information/stacktrace; and notify you by email when your application reports a problem.
Usually you integrate the app's API into your own error handling mechanism. At the point of an error, the client will capture your debugging information, you can popup a modal asking user for information like "what were you doing when this error happened?", save that as part of your error response that is sent back to the service.
Since the app works over HTTP, you don't need any special ports to be open. It is easier and more helpful than having users send you emails with "it doesn't work!!", and you don't have to deal with email sending headaches.
I recently wrote an article on this: Sending email with C#
You basically have two choices, either you send it using an SMTP-client, this means that you have to have a SMTP-server and be able to connect to port 25 (if you're not using an external SMTP, then you have to manage that by yourself). Or you can use an external email provider, such as:
AlphaMail
SendGrid
Mandrill
If you're using AlphaMail you can send emails in the following way:
IEmailService emailService = new AlphaMailEmailService()
.SetServiceUrl("http://api.amail.io/v1/")
.SetApiToken("YOUR-ACCOUNT-API-TOKEN-HERE");
var person = new Person()
{
Id = 1234,
UserName = "jdoe78",
FirstName = "John",
LastName = "Doe",
DateOfBirth = 1978
};
var response = emailService.Queue(new EmailMessagePayload()
.SetProjectId(12345) // ID of AlphaMail project (determines options, template, etc)
.SetSender(new EmailContact("support#company.com", "from#example.com"))
.SetReceiver(new EmailContact("Joe E. Receiver", "to#example.org"))
.SetBodyObject(person) // Any serializable object
);
Another thing that differs from just building HTML and sending it with an SMTP-client is that with AlphaMail you have the ability to edit your emails outside your code directly in a GUI. You can also easily create highly dynamic templates using AlphaMail's templating language Comlang.
<html>
<body>
<b>Name:</b> <# payload.FirstName " " payload.LastName #><br>
<b>Date of Birth:</b> <# payload.DateOfBirth #><br>
<# if (payload.Id != null) { #>
Sign Up Free!
<# } else { #>
Sign In
<# } #>
</body>
</html>
So this is my thought, why don't you have the email sent to you...as you?
using System.Net;
using System.Net.Mail;
var fromAddress = new MailAddress("from#gmail.com", "From Name"); //Both the email addresses would be yours
var toAddress = new MailAddress("to#example.com", "To Name"); //Both the email addresses would be yours
const string fromPassword = "fromPassword";
const string subject = "There name or whatever";
const string body = "Errors ect....";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
code from here
All they would see would be the submit button so they wouldn't have all your personal username/password, also you should prolly set up a dummy account to have them sent to even if it just then forwards them to your real email account.
Another way to achieve this would be to host a WCF Service which takes in your Message and stores in db or /sends email. One downside of this is you'll need a web server to do this.
Try following code this might help you :
Dim objCDOMail
Set objCDOMail = Server.CreateObject("CDONTS.NewMail")
objCDOMail.From = "sender#domain.com"
objCDOMail.To = "receiver#domain.com"
objCDOMail.Subject = "Test Mail Script"
objCDOMail.BodyFormat = 0
objCDOMail.MailFormat = 0
objCDOMail.Body = "Testing Mail from Test Script"
objCDOMail.Importance = 1
objCDOMail.Send
Set objCDOMail = Nothing

C# SMTP sent from server not on the same domain as Exchange is blank

I've just written a piece of code for a MVC website that sends a SMTP email using the .NET SmtpClient via our Exchange server. The email it sends has a HTML body with links to images and a file that are hosted on the website.
The email is sent fine when run internally on our network, but when its run from the hosted server that's not on our domin, the email comes through but the body is blank. Does anybody have any idea why? Is is because of the linked images or file that could be a potential threat and come from a server not on the domain and so is not trusted?
Here's the code that sends the email, it uses the MailDefinition class to insert a link to a file into the body that they've requested to download:
MailDefinition md = new MailDefinition();
md.From = "test#testing.com";
md.Subject = "Test Email";
md.IsBodyHtml = true;
ListDictionary replacements = new ListDictionary();
replacements.Add("REQUESTED_LINK", #"C:\MyFile.pdf");
MailMessage email = md.CreateMailMessage(mailTo, replacements, content, new System.Web.UI.Control());
SmtpClient emailClient = new SmtpClient();
emailClient.Host = "MyExchangeServer";
emailClient.Send(email);
My guess is Value for MailDefinition.BodyFileName missing from the code.
The name of the file that contains the message body text. The default is Empty.
On development or in internal sevrer BodyFileName has a some value. On hosted sevrer file is missing so email Body is empty.
see this Example for reference
Fixed, turns out the .html file containing the body of the email hadn't been deployed to the live server, and so the body of the email was blank as a result. Adding it fixed the problem, so it turns out it wasn't a security issue after all. Thanks for your help

Categories