Send Email from C# using Outlook's - c#

i want to write application who send email using outlook and i found this link.
i try this and it's perfect for me but the only thing that i miss here is the option to attach files to the mail, is it possible to do it ?

Better use MailMessage instead.
There's an example on how to use it with attachment here(Scroll down to "Examples"):
http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.aspx
Not only will you get a managed framework for sending mails, but also whoever runs the code will not need Outlook installed and running.

If you're stuck with outlook for some reason, try this:
using Outlook = Microsoft.Office.Interop.Outlook;
int pos = (int)email.Body.Length + 1;
int attType = (int)Outlook.OlAttachmentType.olByValue;
email.Attachments.Add("file.txt", attType, pos, "File description.");
where:
Outlook.MailItem email = (Outlook.MailItem)_outlookAppInstance.CreateItem(Outlook.OlItemType.olMailItem);

Related

Converting .MSG files to .TXT; Should I use Microsoft.Interop Outlook?

I'm trying to do a conversion from .msg files into .txt. I have two questions.
1)I've been investigating and found the Microsoft.Interop Outlook package and there is a way where I can extract the bodyHTML, To, Sent Date, and a few other properties but I feel as if this is a very manual process because I have to trim out all the html tags such as < br>, &nbsp, a href etc...
Here is my current code...
MailItem mailItem = outlookApp.Session.OpenSharedItem(item) as MailItem;
TextFile textFile = new TextFile(); //collection of properties I am interested in
textFile.To = mailItem.To;
textFile.Subject = mailItem.Subject;
textFile.Sent = mailItem.SentOn.ToString();
textFile.Name = Path.GetFileNameWithoutExtension(item);
var atttach = mailItem.Attachments; //Really just want the names
textFile.Body = RemoveStuff(mailItem.HTMLBody); //manually removing all html tags
textFiles.Add(textFile);
Marshal.ReleaseComObject(mailItem);
Does anyone know if there is a more effective way to do this in C# or a way using Interop that I am not aware of?
2)If I go the interop route, is there a way I can bypass the popup in Outlook asking if I can allow access to Outlook? Seems inefficient if my goal is to create a converter.
Any help is greatly appreciated.
Thanks!
Firstly, why are you using HTMLBody property instead of the plain text Body?
Secondly, you can use MailItem.SaveAs(..., olTxt) to save the message as a text file. Or do you mean something else by txt file?
The security prompt is raised by Outlook if your antivirus app is not up to date. If you cannot control the environment where your code runs, Extended MAPI (C++ or Delphi only) or a wrapper like Redemption (any language - I am its author) are pretty much your only option. See http://www.outlookcode.com/article.aspx?id=52 for more details.
In Redemption, you can have something like the following:
using Redemption;
...
RDOSession session = new RDOSession();
RDOMail msg = session.GetMessageFromMsgFile(TheFileName);
msg.SaveAs(TxtFileName, rdoSaveAsType.olTXT);

Get sub messages from Outlook .msg files

I need to parse a few .msg files which have trail mails. Is there any way to get the sub messages and identify the initiated and the responded emails.
I do not want to use any third party tools. I am allowed to use the Outlook interop.
Below is the code that I have used to read the msg file.I am able to get the Body ,HTMLBody and other details.But I actually need all the trailing messages.
outlook._Application app = null;
outlook.MailItem item = null;
outlook.NameSpace session = null;
try
{
app = new outlook.Application();
session = app.Session;
item = session.OpenSharedItem(file) as outlook.MailItem;
}
catch(Exception ex)
{ }
If you are limited to OOM only, the only way to do that is to save each embedded message attachment as an MSG file (Attachment.SaveAsFile), then open it using Namespace.OpenSharedItem.
If using Redemption (I am its author) is an option, an MSG file can be opened using RDOSession.GetMessageFromMsgFile (similar to Namespace.OpenSharedItem in OOM), and the embedded message attachment can be accessed using the RDOAttachment.EmbeddedMsg property (returns RDOMail object) - no need to save the attachment first.

Convert from .eml to .msg in C# .NET

I want my users to fill out a simple form with fields like From, To, Subject, Body and Attachments. When they are done they should click on a button which lets them download a .msg file, so that they can edit it furthermore in outlook and send it.
All the converters APIs I've found for .NET are commercial (and quite pricy).
Here's my code:
using System.Net.Mail;
protected void lbOpenOutlook_Click(object sender, EventArgs e)
{
CreateEmail();
}
internal void CreateEmail()
{
// Create message
MailMessage message = new MailMessage();
// subject
message.Subject = "email subject";
// body content
message.Body = "email message.";
// sender
message.From = new MailAddress("sender#gmail.com");
// send this mail to
message.To.Add("test1#gmail.com");
// cc list
message.CC.Add("ccuser1#gmail.com");
// Create the SMTP Client object
SmtpClient smtpClient = new SmtpClient();
// store in directory
smtpClient.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
// path of the pickup folder
smtpClient.PickupDirectoryLocation = Server.MapPath("~/Emails/");
// deliver email
smtpClient.Send(message);
}
This generates a .eml file..how could I convert it to a .msg whitout using a commercial API?
Also, I don't want to use Microsoft.Office.Interop.Outlook namespace because it works fine on the client but it's not supported on the server and my application is running under IIS.
Note: Summary of comments on the answer.
Whilst Outlook 2007 does not support opening .eml files, Outlook 2010+ can open .eml files correctly.
To convert EML to MSG you can use Aspose.Email for .Net.
This is a third-party library, which can provide you with a bunch of useful functions for working with email.
The Email API can be used for basic email management features such as converting, message content attachment manipulation and editing, and for its advanced features such as management of the message storage files, sending & receiving emails via several protocols including POP3, IMAP & SMTP.
You can do it programmatically. For example, you can use the following code:
//Initialize .EML file
using (MailMessage eml = new MailMessage("test#from.to", "test#to.to", "template subject", "Template body"))
{
string oftEmlFileName = "EmlAsMSG_out.msg";
MsgSaveOptions options = SaveOptions.DefaultMsg;
//Save created .MSG file
options.SaveAsTemplate = true;
eml.Save(oftEmlFileName, options);
}
I think this approach can be useful for you.
I am a Developer Evangelist at Aspose.

How to open new email with attachment in Windows 10 Mail App

I am trying to add a feature to my C# / .Net app for a user to email a file.
When a user has Outlook installed, I can successfully use the Outlook interop APIs to do exactly what I want.
However on a new Windows 10 install, I cannot work out how to open an email with an attachment in the default Mail app, which is from the Windows Store.
I have tried:
Using EML files, as per https://stackoverflow.com/a/25586282/2102158
The Mail app does not register itself to open EML files
Using the MAPI32.dll etc. (I used the code from https://github.com/metageek-llc/inSSIDer-2/blob/master/MetaScanner/UnhandledException/MapiMailMessage.cs)
A dialog box pops up saying there is no email program registered. It seems the mail app does not interact with MAPI
Using mailto: links.
The mail program opens, but it does not respect Attachment= or Attach= parameters
Also
Windows.ApplicationModel.Email.EmailMessage seems to be only availble on phones.
I do not want to use SMTP to send the message server side.
I also tried the MS-UNISTORE_EMAIL: and OUTLOOKMAIL: url schemes, which are associated to the Mail app, they seemed to behave the same as mailto:
There does not seem to be any way to start the Mail app from the command line
Try this:
a href='mailto:yourname#domain.com?Subject=yoursubject&Body=yourbody&Attachment=file path '
Or try by using file upload to attach the file in mail:
Msg.Attachments.Add(new Attachment(FileUpload1.FileContent, System.IO.Path.GetFileName(FileUpload1.FileName)));
Please try the following example
private async void SendEmailButton_Click(object sender, RoutedEventArgs e)
{
EmailMessage emailMessage = new EmailMessage();
emailMessage.To.Add(new EmailRecipient("***#***.com"));
string messageBody = "Hello World";
emailMessage.Body = messageBody;
StorageFolder MyFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
StorageFile attachmentFile =await MyFolder.GetFileAsync("MyTestFile.txt");
if (attachmentFile != null)
{
var stream = Windows.Storage.Streams.RandomAccessStreamReference.CreateFromFile(attachmentFile);
var attachment = new Windows.ApplicationModel.Email.EmailAttachment(
attachmentFile.Name,
stream);
emailMessage.Attachments.Add(attachment);
}
await EmailManager.ShowComposeNewEmailAsync(emailMessage);
}
The ShowComposeNewEmailAsny(...) part is the magic part.

Get link/path to email in Outlook?

I'm working on an application that's supposed to take a link to an email from Outlook and store it in a database.
I've been looking at the Microsoft.Office.Interop.Outlook API but I can't find something that could be used for this.
Any thoughts?
You could save the email as a .msg file and then save that into the database as a byte array instead?
Otherwise there are ways to programmtically access a mailbox or outlook .pst file, you would then have to write an interface that lets them select the email to save, and then save the email in parts (subject, to, from etc.) separately in to the database.
To access a mailbox on the Exchange server (Exchange 2007+) you can do it using the Exchange Web Services Managed API 1.0. EWS API and you can download it from here
It makes it really simple to access and retrieve emails etc as pre Exchange 2007 it was a pain and involved parsing a lot of XML or using CDOEXM.
Heres an example of how to use it:
You first need to create an Exchange service. Add a reference to the EWS and add the using line below.
using Microsoft.Exchange.WebServices.Data;
...
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
service.AutodiscoverUrl( "First.Last#MyCompany.com" );
Once the service is up and running you can then use it to query the mailbox:
FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox,
new ItemView());
This will return all the emails in the Inbox. You can then view details of the email using its properties. i.e. item.Subject;
If the emails are in a .pst file however, you will need to use the Outlook API or I recommend PST.NET (although you do have to but a license) as it makes it a lot easier.
Heres an example of using PST.NET:
using System;
using Independentsoft.Pst;
namespace Sample
{
class Program
{
static void Main(string[] args)
{
PstFile file = new PstFile("c:\\testfolder\\Outlook.pst");
using (file)
{
Folder inbox = file.MailboxRoot.GetFolder("Inbox");
if (inbox != null)
{
ItemCollection items = inbox.GetItems();
for (int m = 0; m < items.Count; m++)
{
if (items[m] is Message)
{
Message message = (Message)items[m];
Console.WriteLine("Id: " + message.Id);
Console.WriteLine("Subject: " + message.Subject);
Console.WriteLine("DisplayTo: " + message.DisplayTo);
Console.WriteLine("DisplayCc: " + message.DisplayCc);
Console.WriteLine("SenderName: " + message.SenderName);
Console.WriteLine("SenderEmailAddress: " + message.SenderEmailAddress);
Console.WriteLine("----------------------------------------------------------------");
}
}
}
}
Console.WriteLine("Press ENTER to exit.");
Console.Read();
}
}
}
There is no such thing as a link to an email in Outlook.
I suppose that you'd like to store something like shortcut in a text format which can be used later to find/open an email in Outlook. If you plan to use Outlook Interop API for that, you can use EntryID of the MailItem object that represent your email. It's a unique ID of the item, but it can be changed if item is moved somewhere else in the folder structure.

Categories

Resources