I have the following code to send emails automatically when looping through data retrieved from db:
public void sendMailV2(string subject, string body, string emailAddress)
{
// Create the Outlook application.
Outlook.Application oApp = new Outlook.Application();
// Get the NameSpace and Logon information.
Outlook.NameSpace oNS = oApp.GetNamespace("mapi");
// Log on by using a dialog box to choose the profile.
oNS.Logon(Missing.Value, Missing.Value, true, true);
// Alternate logon method that uses a specific profile.
// TODO: If you use this logon method,
// change the profile name to an appropriate value.
//oNS.Logon("YourValidProfile", Missing.Value, false, true);
// Create a new mail item.
Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
// Set the subject.
oMsg.Subject = subject;
// Set HTMLBody.
oMsg.HTMLBody = body;
// Add a recipient.
Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
// TODO: Change the recipient in the next line if necessary.
Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add(emailAddress);
oRecip.Resolve();
// Send.
oMsg.Send();
// Log off.
oNS.Logoff();
// Clean up.
oRecip = null;
oRecips = null;
oMsg = null;
oNS = null;
oApp = null;
}
However, I want the emails to be sent from the server, not my own outlook. I have the username and password for the server(someserver#serving.com) but I can't figure out how and where to implement them.
I would appreciate any help.
First of all, there is no need to create a new Application instance if you need to send multiple emails. You may consider moving the following lines of code outside of the method and create the Application instance at the global scope.
// Create the Outlook application.
Outlook.Application oApp = new Outlook.Application();
If you have got another accounts configured in Outlook, you can use the SendUsingAccount property of the MailItem class which allows to set an Account object that represents the account under which the MailItem is to be sent.
If you don't have the required account configured in Outlook you may consider using the BCL classes for getting the job done. See How to send email from C# for more information.
Related
here's my attempt:
Outlook.Application app = new Outlook.Application();
RDOSession session = new RDOSession();
session.MAPIOBJECT = app.Session.MAPIOBJECT;
RDOFolder inbox = session.GetDefaultFolder(rdoDefaultFolders.olFolderInbox);
RDOItems items = inbox.Items;
RDOMail mail = items.GetFirst();
if (mail.MessageClass == "IPM.Note.SMIME") {
RDOEncryptedMessage encryptedMessage = (RDOEncryptedMessage)session.GetMessageFromID(mail.EntryID)
// from here I am stuck because encryptedMessage is null
}
What am I doing wrong ?
Why do you call GetMessageFromID instead of casting mail to RDOEncryptedMessage? Are you sure you actually get an encrypted message from Items.GetFirst? Do not expect to get the very first message you see in Outlook - you do not sort the Items collection, and most likely GetFirst will return the oldest message in the folder, not the topmost message you see in Outlook's explorer.
I`m trying to create outlook mails from templates, slightly edit them and then show to user so he can send that mail.
There is no problem in creation of the mail and displaying it. But when I`m trying to read (or edit) HTMLBody of the mail there is a error:
Operation aborted (Exception from HRESULT: 0x80004004 (E_ABORT))
Here is my code:
using Outlook = Microsoft.Office.Interop.Outlook;
...
try
{
var app = new Outlook.Application();
Outlook.MailItem mailItem = app.CreateItemFromTemplate("C:\\Test\\template.oft");
var body = mailItem.HTMLBody; //Here is the exception
mailItem.HTMLBody = body.Replace("#firstname", "Test Testy");
mailItem.To = message.EmailAddress;
mailItem.Display(mailItem);
}
catch (Exception ex)
{
...
}
Added example project on github.
var app = new Outlook.Application();
Before creating a new instance of the Outlook Application class I'd suggest checking whether it is already run and get the running instance then:
if (Process.GetProcessesByName("OUTLOOK").Any())
app = System.Runtime.InteropServices.Marshal.GetActiveObject("Outlook.Application");
Outlook is a singleton. You can't run multiple instances at the same time.
Also I'd suggest saving the newvly created item before accessing the HTMLBody property value:
Outlook.MailItem mailItem = app.CreateItemFromTemplate("C:\\Test\\template.oft");
mailIte.Save();
var body = mailItem.HTMLBody; //Here is the exception
Finally, the Display method doesn't take a MailItem instance. Instead, you can pass true to get the inspector shown as a modal window or just omit the parameter (false is used by default).
BTW Where and when do you run the code?
I have two mailboxes setup in Outlook.
I'll refer to them as "email1#mail.com" and "email2#mail.com".
I would like to use Interop to create and send an appointment to a specific email address calender, not just to the default outlook account.
using System;
using System.Diagnostics;
using System.Reflection;
using Outlook = Microsoft.Office.Interop.Outlook;
namespace Program
{
class Program
{
public static void Main(string[] args)
{
// Create the Outlook application.
Microsoft.Office.Interop.Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.Application();
Outlook.Account account = oApp.Session.Accounts["email2#mail.com"];
// Get the NameSpace and Logon information.
Microsoft.Office.Interop.Outlook.NameSpace oNS = oApp.GetNamespace("mapi");
// Log on by using a dialog box to choose the profile.
oNS.Logon(Missing.Value, Missing.Value, true, true);
// Create a new mail item.
Microsoft.Office.Interop.Outlook.MailItem oMsg =(Microsoft.Office.Interop.Outlook.MailItem) oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
// Set the subject.
oMsg.Subject = "test";
// Set HTMLBody.
oMsg.HTMLBody = "test";
oMsg.To = "test#gmail.com";
//oMsg.CC = _cc;
//oMsg.BCC = _bcc;
oMsg.Save();
oMsg.SendUsingAccount = account;
// Add a recipient.
//Microsoft.Office.Interop.Outlook.Recipients oRecips = (Microsoft.Office.Interop.Outlook.Recipients)oMsg.Recipients;
// TODO: Change the recipient in the next line if necessary.
//Microsoft.Office.Interop.Outlook.Recipient oRecip = (Microsoft.Office.Interop.Outlook.Recipient)oRecips.Add(_recipient);
//oRecip.Resolve();
// Send.
(oMsg as Microsoft.Office.Interop.Outlook._MailItem).Send();
// Log off.
oNS.Logoff();
// Clean up.
//oRecip = null;
//oRecips = null;
oMsg = null;
oNS = null;
oApp = null;
}
}
}
This code works flawlessly in sending an email automatically to "test#gmail.com" from my email "email2#mail.com".
However, I would like to automatically create an appointment/meeting for a specific email address.
This is my current attempt:
using System;
using System.Diagnostics;
using System.Reflection;
using Outlook = Microsoft.Office.Interop.Outlook;
namespace SendEventToOutlook
{
class Program
{
public static void Main(string[] args)
{
try
{
// Create the Outlook application.
Microsoft.Office.Interop.Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.Application();
Outlook.Account account = oApp.Session.Accounts["email2#mail.com"];
// Get the nameSpace and logon information.
Microsoft.Office.Interop.Outlook.NameSpace oNS = oApp.GetNamespace("mapi");
// Log on by using a dialog box to choose the profile.
oNS.Logon(Missing.Value, Missing.Value, true, true);
// Create a new Appointment item.
Microsoft.Office.Interop.Outlook.AppointmentItem appt =
(Microsoft.Office.Interop.Outlook.AppointmentItem)
oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olAppointmentItem);
appt.Start = DateTime.Now;
appt.End = DateTime.Now.AddDays(7);
appt.Location = "Test";
appt.Body = "Test";
appt.AllDayEvent = false;
appt.Subject = "Test";
appt.Save();
appt.SendUsingAccount = account;
// Log off.
oNS.Logoff();
appt = null;
oNS = null;
oApp = null;
}
catch (Exception ex)
{
Debug.WriteLine("The following error occurred: " + ex.Message);
}
}
}
}
This code does create an appointment successfully, but it keeps creating an appointment for "email1#mail.com" instead of "email2#mail.com", which shouldn't happen as I've specified the sending account to be "email2#mail.com" from the lines:
Outlook.Account account = oApp.Session.Accounts["email2#mail.com"];
and then
appt.SendUsingAccount = account;
This is how my two email addresses are set up in Outlook: http://i.imgur.com/0eopV8A.png
Both the email addresses have different user names and are from different domains/mail servers, as shown in that screenshot.
Would anyone be able to see the problem I'm making or if there's a different solution?
Thank you.
It is not clear whether you have got two accounts set up in the single Mail profile or separate profiles.
The SendUsingAccount property of the AppointmentItem class allows to set an Account object that represents the account under which the AppointmentItem is to be sent. So, The SendUsingAccount property can be used to specify the account that should be used to send the AppointmentItem when the Send method is called. It is not what you are looking for I suppose.
Anyway, you can use the GetDefaultFolder method of the Store class which returns a Folder object that represents the default folder in the store and that is of the type specified by the FolderType argument. This method is similar to the GetDefaultFolder method of the NameSpace object. The difference is that this method gets the default folder on the delivery store that is associated with the account, whereas NameSpace.GetDefaultFolder returns the default folder on the default store for the current profile.
Thus, you can get the Calendar folder for the required account and add a new appointment there.
You may find the following articles in MSDN helpful:
How to: Create a Sendable Item for a Specific Account Based on the Current Folder (Outlook)
Using Multiple Accounts for the Same Profile on Outlook
I'm new to C#. I've found how to create an outlook email from C#:
// Create a new MailItem.
Outlook._MailItem oMsg1;
oMsg1 = oApp.CreateItem(Outlook.OlItemType.olMailItem);
oMsg1.To = "amine#gmail.com";
oMsg1.Subject = "Test Subject";
oMsg1.Body = "test Body";
Outlook.Attachments oAttachs1 = oMsg1.Attachments;
// Add an attachment
string sSource1 = "C:\\testFile.xls";
Outlook.Attachment oAttach1;
oAttach1 = oAttachs1.Add(sSource1);
oMsg1.Display(true);
oApp = null;
oMsg1 = null;
oAttach1 = null;
oAttachs1 = null;
But I want to create multiple emails at the same time. So Outlook will display multiple email windows.
I tried a for loop to create multiple mailItem but this didn't work. Outlook displays only the first email.
Any idea ? Thanks!
Use oMsg1.Display(false);
When set to True, oMsg1.Display(true) means Outlook creates a 'Modal' window, meaning it freezes that particular email until it is sent or discarded.
in my outlook addin I want to add a button on the Ribbon so when user click this button I want to retrieve the current selected email's body , I have this code but it retrieve only the first email from the inbox because the index is 1 :
Microsoft.Office.Interop.Outlook.Application myApp = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.NameSpace mapiNameSpace = myApp.GetNamespace("MAPI");
Microsoft.Office.Interop.Outlook.MAPIFolder myInbox = mapiNameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
String body = ((Microsoft.Office.Interop.Outlook.MailItem)myInbox.Items[1]).Body;
so how to retrieve the current opened email in outlook? , this method work for me but I need to get the index for the current email.
Thanks.
You shouldn’t initialize a new Outlook.Application() instance each time. Most add-in frameworks provide you with an Outlook.Application instance, corresponding to the current Outlook session, typically through a field or property named Application. You are expected to use this for the lifetime of your add-in.
To get the currently-selected item, use:
Outlook.Explorer explorer = this.Application.ActiveExplorer();
Outlook.Selection selection = explorer.Selection;
if (selection.Count > 0) // Check that selection is not empty.
{
object selectedItem = selection[1]; // Index is one-based.
Outlook.MailItem mailItem = selectedItem as Outlook.MailItem;
if (mailItem != null) // Check that selected item is a message.
{
// Process mail item here.
}
}
Note that the above will let you process the first selected item. If you have multiple items selected, you might want to process them in a loop.
On Top add reference to
using Outlook = Microsoft.Office.Interop.Outlook;
Then inside a method;
Outlook._Application oApp = new Outlook.Application();
if (oApp.ActiveExplorer().Selection.Count > 0)
{
Object selObject = oApp.ActiveExplorer().Selection[1];
if (selObject is Outlook.MailItem)
{
Outlook.MailItem mailItem = (selObject as Outlook.MailItem);
String htmlBody = mailItem.HTMLBody;
String Body = mailItem.Body;
}
}
Also you can change the body which will show in outlook before viewing the mail.