Tuesday, October 18, 2011

Send an E-Mail Given the SMTP Address of an Account

//Namespaces to use


using Outlook = Microsoft.Office.Interop.Outlook;
using System;
using System.Text;
using Outlook = Microsoft.Office.Interop.Outlook;
// code to send mail
namespace OutlookAddIn1
{
    class Sample
    {
        public static void SendEmailFromAccount(Outlook.Application application, string subject, string body, string to, string smtpAddress)
        {

            // Create a new MailItem and set the To, Subject, and Body properties.
            Outlook.MailItem newMail = (Outlook.MailItem)application.CreateItem(Outlook.OlItemType.olMailItem);
            newMail.To = to;
            newMail.Subject = subject;
            newMail.Body = body;

            // Retrieve the account that has the specific SMTP address.
            Outlook.Account account = GetAccountForEmailAddress(application, smtpAddress);
            // Use this account to send the e-mail.
            newMail.SendUsingAccount = account;
            newMail.Send();
        }


        public static Outlook.Account GetAccountForEmailAddress(Outlook.Application application, string smtpAddress)
        {

            // Loop over the Accounts collection of the current Outlook session.
            Outlook.Accounts accounts = application.Session.Accounts;
            foreach (Outlook.Account account in accounts)
            {
                // When the e-mail address matches, return the account.
                if (account.SmtpAddress == smtpAddress)
                {
                    return account;
                }
            }
            throw new System.Exception(string.Format("No Account with SmtpAddress: {0} exists!", smtpAddress));
        }

    }
}

No comments:

Post a Comment

Thank you for Commenting Will reply soon ......

Featured Posts

Open Hardware Monitor A Handy Tool for System Monitoring

#Open #Hardware #Monitor: A Handy Tool for #System #Monitoring #OpenHardwareMonitor is a free, #opensource #software designed to monitor t...