Generate Oulook Email From Server - c#

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

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.

How do I programmatically send encrypted emails in Outlook Express using Python?

I'm a new programmer and I've reached the point where my lack of knowledge (of the C# and VBA language) and experience is preventing me from continuing with my program. I only know Python and all the documentation that I've tried digging into is in C# and VB.
My story: I'm working on a GUI that automates and manages specialized email operations for my company using Outlook Express 2016. I've figured out that win32com is the package to use, and I've figured out how to create and send basic emails, but I'm struggling to figure out how to send emails encrypted. My company uses the McAfee SaaS Email Encryption add-in found at: http://www.mcafee.com/us/downloads/saas/encrypted-from-microsoft-outlook-addin.aspx.
Note: the site doesn't specify that this add-in is supported in the 2016 version but it indeed works. Also, the built-in Outlook option to encrypt all emails is not viable because I need some emails to not be encrypted.
What I've garnered from another similar post is that I need to use the PropertyAccessor method:
mailItem.PropertyAccessor.SetProperty(
"http://schemas.microsoft.com/mapi/proptag/0xHHHHHHHH", x);
where HHHHHHHH is some hexadecimal code and x represents a state such as 0 = off. I tried digging into some property tag documentation but I'm having trouble understanding them.
Am I on the right track? There may be a completely different + easier way of doing this. I do realize a lot of my difficulty may be due to not knowing C#/VBA, but it would be highly appreciated if someone out there can point me in the right direction.
First, you need a Secure Email certificate issued to the email address you want to use.
Let's say this is mymail.somecompany.com. Your cert should have this in the subject name and should be enabled for secure email.
Next, you need to programmatically get the certificate or load from a pfx file like
X509Store store = new X509Store(StoreLocation.CurrentUser);
store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
X509Certificate2Collection certs = store.Certificates;
X509Certificate2 certificate = null;
foreach (X509Certificate2 cert in certs)
{
if (cert.Subject.IndexOf("mymail#somecompany.com") >= 0)
{
certificate = cert;
break;
}
}
Next, you need to have an entity that you want to sign and send.
string strbody = #"Content-Type: text/plain;charset=""iso-8859-1""
Content-Transfer-Encoding: quoted-printable
This is a test s/mime message";
This is where it gets a little not very intuitive since there is no programatic way of creating the email entity you want to send
Note the headers and a series of two \r\n before the entity body "this is a test s/mime" message begins
Next, you need to generate a signed envelope for this content
byte[] data = Encoding.ASCII.GetBytes(strbody);
ContentInfo content = new ContentInfo(data);
SignedCms signedCms = new SignedCms(content, false);
CmsSigner signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, certificate);
signedCms.ComputeSignature(signer);
byte[] signedbytes = signedCms.Encode();
Now that you have the content you want to send is signed with the certificate of your choice you need to
create a mail message object and create an alternate view and add this to your alternate view collection
MailMessage msg = new MailMessage();
msg.From = new MailAddress("");
msg.To.Add(new MailAddress(""));
msg.Subject = "test s/mime";
MemoryStream ms = new MemoryStream(signedbytes);
AlternateView av = new AlternateView(ms, "application/pkcs7-mime; smime-type=signed-data;name=smime.p7m");
msg.AlternateViews.Add(av);
Now that you have the message prepared you can just send it
SmtpClient client = new SmtpClient("smtphost", 25);
client.UseDefaultCredentials = true;
client.Send(msg);
This is a kind of hack at this time and requires some manual preparation of the entity body
you want to sign. I need to do some more research on this and find out if there is a better way of doing this.

Selenium Webdriver automation with emails

I'm currently trying to use Selenium Webdriver (C#) to automate a Forgot Password -> Reset Password workflow, where the user navigates to a page and supplies their username, and the backend code validates the username, then sends an email with a reset password link to the email address associated with their account.
I'm able to automate the process up to the point where the code sends the email, but I don't know any ways of checking for the email and/or clicking a link in the email, so I was hoping someone more experienced with Selenium/automation may be able to give me a few pointers.
Ideally the test should not care about the email address that the email is being sent to. Is there a way for Selenium WebDriver or some 3rd party package to catch the email being sent?
Thanks for any input or suggestions.
No. You are talking about setting up an email server, which is not an easy task.
You should send it to a test work email (if this is for a company), or a public email (hotmail/gmail), or if security is not an issue at all, the easiest place to send it would be a disposable email (mailinator)
You could try PutsBox. You can send an email to whatever-you-want#putsbox.com, wait for a few seconds (SMTP stuff ins't instantaneous) then check your email via http://preview.putsbox.com/p/whatever-you-want/last.
Have a look at this post tutorial, it can give you some ideas.
There is no integration of selenium with email clients like Thunderbird/Outlook. But if you have a web interface of the same email client, then you can access the email from browser and using selenium you can read and respond to the emails. I have tried this recently and it works fine where I have used web Outlook for testing.
Hope this helps.
Hi I was in a similar situation and was able to successfully implement a way to get an activation or forgotten password links.
Using Java Mail API I was able to trigger a method when such action is performed which goes into a Folder and read a specific message line then get the link and open it up in a browser using WebDriver.
However the main drawback with this is the inconsistency of reading a specific folder, sometimes emails goes to spam or other folder (in case of Gmail the new Social Folder) making it invisible or difficult to be retrieved.
Overall i think its a process that shouldn't really be automated, In terms of testing it should be done more code base level by mocking responses.
Snippet below should give you an idea on how to go about implementing
public class RefactoredMail {
public static void main(String[] args) {
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getInstance(props, null);
Store store = session.getStore();
store.connect("imap.gmail.com", "username", "password");
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Message msg = inbox.getMessage(inbox.getMessageCount());
Address[] in = msg.getFrom();
for (Address address : in) {
System.out.println("FROM:" + address.toString());
}
Multipart mp = (Multipart) msg.getContent();
BodyPart bp = mp.getBodyPart(0);
System.out.println("SENT DATE:" + msg.getSentDate());
System.out.println("SUBJECT:" + msg.getSubject());
System.out.println("CONTENT:" + bp.getContent());
System.out.println("Activation Link:" + ((String)
bp.getContent()).startsWith("http"));
String [] line = new String[1];
line [0] = mp.getContentType().toString();
System.out.println("Activation Link:" + (mp.getBodyPart(0).getLineCount()));
System.out.println("Activation Link:" +line[0]);
} catch (Exception e) {
e.printStackTrace();
}
//WebDriver Stuffs
public String activationUrl() {
//getting the url link and making it a global variable .... etc
//Accessing the link
}
}
You can use https://github.com/cmendible/netDumbster or http://ndumbster.sourceforge.net/default.html. I've used one i forget which. This will host an smtp listener and allow you to make assertions against any email it receives. Its kind of awesome! The caveat is you need to be able to control where the server delivers mail in the environment you are testing.

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

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.

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

Categories