Compartilhar via


How to: Programmatically send email

Applies to: yesVisual Studio noVisual Studio for Mac

Note

This article applies to Visual Studio 2017. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here

This example sends an email message to contacts that have the domain name example.com in their email addresses.

Applies to: The information in this topic applies to VSTO Add-in projects for Outlook. For more information, see Features available by Office application and project type.

Note

Interested in developing solutions that extend the Office experience across multiple platforms? Check out the new Office Add-ins model. Office Add-ins have a small footprint compared to VSTO Add-ins and solutions, and you can build them by using almost any web programming technology, such as HTML5, JavaScript, CSS3, and XML.

Example

private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
    SendEmailtoContacts();
}

private void SendEmailtoContacts()
{
    string subjectEmail = "Meeting has been rescheduled.";
    string bodyEmail = "Meeting is one hour later.";
    Outlook.MAPIFolder sentContacts = (Outlook.MAPIFolder)
        this.Application.ActiveExplorer().Session.GetDefaultFolder
        (Outlook.OlDefaultFolders.olFolderContacts);
    foreach (Outlook.ContactItem contact in sentContacts.Items)
    {
        if (contact.Email1Address.Contains("example.com"))
        {
            this.CreateEmailItem(subjectEmail, contact
                .Email1Address, bodyEmail);
        }
    }
}

private void CreateEmailItem(string subjectEmail,
       string toEmail, string bodyEmail)
{
    Outlook.MailItem eMail = (Outlook.MailItem)
        this.Application.CreateItem(Outlook.OlItemType.olMailItem);
    eMail.Subject = subjectEmail;
    eMail.To = toEmail;
    eMail.Body = bodyEmail;
    eMail.Importance = Outlook.OlImportance.olImportanceLow;
    ((Outlook._MailItem)eMail).Send();
}

Compile the code

This example requires:

  • Contacts that have the domain name example.com in their email addresses.

Robust programming

Do not remove the filter code that searches for the domain name example.com. Your solution will send email messages to all of your contacts if you remove the filter.

See also