Mail from excel with outlook

  • Интернет
  • Рассылка почты

Пример макроса, отправляющего письма со вложениями из Excel через почтовый клиент Outlook:

Sub Отправить_Письмо_из_Outlook()
 
    'отправляем письмо без вложений
    res = SendEmailUsingOutlook("name@domain.ru", "Текст письма 1", "Тема письма 1")
    If res Then Debug.Print "Письмо 1 отправлено успешно" Else Debug.Print "Ошибка отправки"
 
 
    'отправляем письмо с 1 вложением
    attach$ = ThisWorkbook.FullName    ' прикрепляем текущий файл Excel
    res = SendEmailUsingOutlook("name@domain.ru", "Текст письма 2", "Тема письма 2", attach$)
    If res Then Debug.Print "Письмо 2 отправлено успешно" Else Debug.Print "Ошибка отправки"
 
 
    'отправляем письмо с несколькими вложениями
    Dim coll As New Collection    ' заносим в коллекцию список прикрепляемых файлов
    coll.Add "C:Documents and SettingsAdminРабочий столTyres.jpg"
    coll.Add "C:Documents and SettingsAdminРабочий столcalc.xls"
    coll.Add ThisWorkbook.FullName    ' прикрепляем текущий файл Excel

    res = SendEmailUsingOutlook("name@domain.ru", "Текст письма 3", "Тема письма 3", coll)
    If res Then Debug.Print "Письмо 3 отправлено успешно" Else Debug.Print "Ошибка отправки"
End Sub

Макрос использует функцию SendEmailUsingOutlook, которая:

  • принимает в качестве параметров адрес получателя письма, тему и текст письма, список вложений
  • запускает Outlook, формирует письмо, и отправляет его
  • возвращает TRUE, если отправка прошла успешно, или FALSE, если с отправкой почты вызникли проблемы

Код функции SendEmailUsingOutlook:

Function SendEmailUsingOutlook(ByVal Email$, ByVal MailText$, Optional ByVal Subject$ = "", _
                               Optional ByVal AttachFilename As Variant) As Boolean
    ' функция производит отправку письма с заданной темой и текстом на адрес Email
    ' с почтового ящика, настроенного в Outlook для отправки писем "по-умолчанию"
    ' Если задан параметр AttachFilename, к отправляемому письму прикрепляется файл (файлы)

    On Error Resume Next: Err.Clear
    Dim OA As Object: Set OA = CreateObject("Outlook.Application")
    If OA Is Nothing Then MsgBox "Не удалось запустить OUTLOOK для отправки почты", vbCritical: Exit Function
 
    With OA.CreateItem(0)   'создаем новое сообщение
        .To = Email$: .Subject = Subject$: .Body = MailText$
        If VarType(AttachFilename) = vbString Then .Attachments.Add AttachFilename
        If VarType(AttachFilename) = vbObject Then    ' AttachFilename as Collection
            For Each file In AttachFilename: .Attachments.Add file: Next
        End If
        For i = 1 To 100000: DoEvents: Next    ' без паузы не отправляются письма без вложений
        Err.Clear: .Send
        SendEmailUsingOutlook = Err = 0
    End With
    Set OutApp = Nothing
End Function

Пример макроса, с получением параметров письма из ячеек листа Excel: 

Sub Отправить_Письмо_из_Outlook()
    ' адрес получателя - в ячейке A1, текст письма - в ячейке A2
    res = SendEmailUsingOutlook(Cells(1, 1), Range("a2"), "Тема письма 1")
    If res Then Debug.Print "Письмо 1 отправлено успешно" Else Debug.Print "Ошибка отправки"
End Sub
  • 176126 просмотров

Не получается применить макрос? Не удаётся изменить код под свои нужды?

Оформите заказ у нас на сайте, не забыв прикрепить примеры файлов, и описать, что и как должно работать.

In this post we’re going to learn how to send emails from Excel. It’s possible to do this using VBA, but that’s the old way from the 90’s and we’re in 2018.

We are going to explore Microsoft Flow. This is a new product from Microsoft that allows us to automate workflows between apps. It’s not just Microsoft Office apps that can be automated. There are a ton of third party connections available. We can easily create rules that automatically do things like:

  • Save any email attachments to a OneDrive folder.
  • Get a notification on your phone when someone updates a table in your spreadsheet.
  • Track all company Twitter mentions in a spreadsheet.
  • Sync your Outlook calendar to your Google calendar.
  • Forward emails to Slack.

The awesome part about Microsoft Flow is that it requires no code! We can design and build out your process (flow) in a couple minutes with an easy to use graphical interface.

In this post, we’ll be building a flow that schedules and sends an email template from Outlook based on the data in an Excel file.

Sign Up for Microsoft Flow

For this post, we’ll need to sign up for a Microsoft Flow account or sign into an existing Office 365 account.

There’s a free version which allows for 750 flows a month. If you have Office 365, then you already have Microsoft Flow and can use up to 2,000 flows per month.

Head to the Microsoft Flow website at https://flow.microsoft.com and click on either the Sign in or Sign up free button. Then either log in with your Office 365 credentials or provide the necessary information to create an account.

In the flow recipe we’ll be creating in this post, we’ll also need a OneDrive account. If you have Office 365, then you already have a OneDrive account. If not, then you can easily create a free one here https://onedrive.live.com.

A Quick Tour of Microsoft Flow

My Flows

In the My Flows tab of the site, we see all our flows listed that we have built. There’s a lot that can be done from this page.

  • There’s an icon that shows which connections have been used for the flow.
  • The name of the flow is listed.
  • We can deactivate a flow to temporality stop it from running.
  • We can share a flow with another user.
  • We can edit a flow.
  • We can create new flows either based on an existing template or starting from scratch with a blank flow.

Approvals

Flows allow us to create approval steps in our processes.

Imagine creating a flow to automatically email a quote generated from a spreadsheet to a potential client. You might want someone to review it and approve the email before it is actually sent. This is a step that can be added to any flow and is all managed from the Approvals tab.

Templates

A lot of what we may want to create might have already been built by the Microsoft team or someone else. In the Templates tab, there are a ton of pre-built flows that you can use as is, or customize for your use.

Click on any of the templates and see a more detailed explanation of what the flow does and what it needs to connect with to work.

Connectors

Connectors are the pieces you use to build out your automated process. In the Connectors tab, there are a ton of connections available for just about every popular online service including all the office applications.

There are many connections.

  • Office apps like Excel, Outlook, OneDrive etc…
  • Other Microsoft products like PowerApps and Power BI.
  • Google office productivity suite.
  • Twitter, Facebook, YouTube and other social apps.
  • Many other online tools.

We can click on any of the connections to see further details about what type of actions we can do with it.

Setting Up Our Excel File

The first thing we’re going to need to do is set up our Excel File in OneDrive. We can create a new Excel workbook in OneDrive and add data to it for use with our emails.

In this example, we’re going to be creating and sending emails from Outlook based on the data in Excel. For each row of data, we are going to be sending the client an email telling them the current account balance that is owed.

We don’t need to create the whole email in Excel, just the data for the parts that will be different for each email we want to send.

  • Date – We are going to delay sending out our emails based on this date.
  • Email Address – This is the email address we are going to send an email to.
  • Name – This is going to be used in body of the email to address the recipient by name.
  • Account Balance – This is going to be used in the body of the email to tell the recipient their current account balance.

We will need to add the data into an Excel Table, as this is the only Excel object that Microsoft Flow will recognize.

To create a table, we can select the data and go to the Insert tab and use the Table command. We can also use the Ctrl + T keyboard shortcut to create a table.

Once we have a table with our data, we need to make sure to give it a good name instead of the default Table1 name. With the table selected we can go to the Table Tools Design tab and give it a new name from the Properties section. We will name the table Emails.

This will make any flows created with the data a lot easier to understand later on. Proper column heading names will help later on too.

Creating Our First Blank Flow

When logged into Microsoft Flow, go to the My flows tab and click on the Create from Blank button. The next screen will show you some popular triggers to start your flow with, but we want a blank flow, so we can click on the Create from blank button again.

Adding Our Flow Trigger

The first thing we need to do when creating our flow is add a trigger. This is exactly what it sounds like, it’s something that will trigger the flow to execute.

In this case, we’re going to create a button that we can press from the Microsoft Flow app to run the flow.

  1. Search for button to narrow down the list of available triggers and find the mobile button.
  2. Select Flow button for mobile from the connection options.
  3. Choose the Triggers section of the results. Each connection might have several trigger and action options available.
  4. Click on the Flow button for mobile trigger.

Getting Data from Excel to the Flow

After we trigger our flow with the button, we’re going to want it to do something. These will be the actions we add in the next steps of our flow process.

The first action we want to do is get the data from our Excel table.

Click on the New step button to add the next step to the flow. Then select Add an action from the menu.

Search for Excel to narrow down the list of connections then select the Excel – Get rows action. This action will get all the rows of data from the specified table in a given workbook.

Now we can select the File name from our OneDrive using the file icon and then select the appropriate Table name from the drop down menu, our table was named Emails.

Creating a Delay Based on the Date Field in Excel

In this example, we want to send each email out at a particular date and time based on the Date field in the Excel data. We can add a schedule step into the flow to accomplish this.

Create a New step and Add an action. Then search for delay and choose the Schedule – Delay until action.

The delay step will require a timestamp input. We can hard code a single value here, but it’s also possible to Add dynamic content so the timestamp depends on the values in our Excel file. Note, that flow will interpret the timestamp data in Excel as being UTC.

Click into the timestamp input field and the dynamic content pop up will display.

Under the Get rows section of the dynamic content pop up, select the Date field from our Excel table.

When we add the date from our Get rows action, something sort of magical happens. Flow will automatically place the delay step inside an Apply to Each step. Flow realizes we don’t want to just perform our actions once, but we likely want to perform our actions for each row of data in the Excel table.

This is exactly what we want. We could have added this in ourselves before adding the delay step. But it’s nice to know it’ll tell us if we forget.

Create the Email Template for Each Row of Data

Now we are ready to add our email step after the delay. This will be added inside the Apply to Each step since we want to send an email for each row of the data in our table.

Press the Add an action button found inside the Apply to each step.

This time we can search for Outlook to narrow down the results and choose the Office 365 Outlook – Send an email action.

We can then create an email template, referencing fields from our data where appropriate. In the To input section we would add our Email Address field from our data since this contains the email address to which we want to send the email.

Add a Notification Step

Since this flow will delay the emails, we might want some sort of confirmation when each email is actually sent. For this, we could add a notification step. This will send us a notification when each email is sent.

Again, we want this step inside the Apply to each step, so press the Add an action button at the bottom of the Apply to each step. Search for notification to narrow down the results and choose the Notifications – Send me a mobile notification action.

We can then add Text to the alert to specify which email was sent.

To actually receive the notification on our mobile device, we will need to install the Microsoft Flow app. We can download either the Android app here or the Apple app here.

Saving and Naming the Flow

Now that we’ve finished building our flow process, we need to save it. Click on the Save icon in the upper right hand corner of the web app.

We’ll also want to give the new flow a descriptive name. Click on the default name found in the top left hand corner of the web app then rename it appropriately.

Running the Flow

Now that we’ve built our flow process, named and saved it, we are ready to use it. We can now run the flow a few different ways.

Since the trigger we created to run the flow was the mobile app button, we can run the flow from our mobile device with the app installed. Go to the Buttons section of the mobile app, then press the button for our email flow.

We can also run the flow from the web app in the My flows tab. Click on the 3 ellipse icon on the right side of the flow and choose Run now from the options.

Either method will start the flow.

If the date field is in the past, then those emails will be sent immediately. Future dates will have emails delayed. Even though future dated emails are not sent, they are still created by flow, so changing the data in the Excel table after running will not change future dated emails.

Conclusions

Microsoft Flow is simple to use and very powerful. We’re in the modern era and no longer need to be programmers to create useful automation’s that save tons of time.

We were able to easily create a flow that sends emails based on the data in a connected Excel table.

If you can use a mouse and have some ideas about processes you’d like to automate, then Microsoft Flow is meant for you.

I’d love to hear about all the cool things you build with Microsoft Flow, so let me know in the comments below!

About the Author

John MacDougall

John is a Microsoft MVP and qualified actuary with over 15 years of experience. He has worked in a variety of industries, including insurance, ad tech, and most recently Power Platform consulting. He is a keen problem solver and has a passion for using technology to make businesses more efficient.

Project Online Desktop Client Publisher for Microsoft 365 Excel 2021 Word 2021 PowerPoint 2021 Project Professional 2021 Project Standard 2021 Publisher 2021 Excel 2019 Word 2019 PowerPoint 2019 Project Professional 2019 Project Standard 2019 Publisher 2019 Excel 2016 Word 2016 PowerPoint 2016 Project Professional 2016 Project Standard 2016 Publisher 2016 Excel 2013 Word 2013 PowerPoint 2013 Project Professional 2013 Project Standard 2013 Publisher 2013 Excel 2010 Word 2010 Project 2010 Project Standard 2010 Publisher 2010 More…Less

If you have Outlook installed as part of Microsoft Office, and set as your default email app, you can send your document as an email attachment. If you are using Excel, Publisher, or Word, you can also send your file as the body of an email message.

If Outlook is not your default email application you’ll need to configure it as the default in order to use this feature. For more information see: Make Outlook the default program for email, contacts, and calendar. 

Send as an attachment

Excel, PowerPoint, and Word

  1. Click File > Share, and then choose one of the following options:

    Note: The options you see will vary depending on the Office program you’re using.

    • Upload to OneDrive    Uploads your file to your OneDrive account where you can then share through a direct link or an email message.

    • Attach a copy instead    Choose to attach a the file to an email, or attach a PDF of the file.

  2. Enter the recipients’ aliases, edit the subject line and message body as necessary, and then click Send.

OneNote, Visio, Publisher, and Project

  1. Click File > Share, and then choose one of the following options:

    Note: The options you see will vary depending on the Office program you’re using.

    • Share with People (OneNote and Visio)    Lets you enter name or email address for who you want to send to, set whether you want them to edit, require the user signs in before editing, and an optional message.

      This option requires that your file is uploaded to OneDrive.

    • Send a Link (Visio)    Allows everyone to work on the same copy of the file, see the latest changes, and keeps your email size small.

      To send a link, the file must be saved to a Web server or shared folder.

    • Send as Attachment    Opens an email message with a copy of the file in its original file format attached.

    • Send as PDF    Opens an email message with a copy of the file in .pdf format attached.

    • Send as XPS    Opens an email message with a copy of the file in .xps format attached.

  2. Enter the recipients’ aliases, edit the subject line and message body as necessary, and then click Send.

Send as the body of an email message

If you are using Excel, Publisher, or Word, you can send your file as the actual email message content — not as an attachment. To do this, first you need to add the Send to Mail Recipient command to the Quick Access Toolbar. See Customize the Quick Access Toolbar to learn how to add commands.

  1. Open the file you want to send.

  2. In the Quick Access Toolbar, click Send to Mail Recipient to open an email message. Your file will appear in the body of the message.

  3. Enter the recipients’ aliases, edit the subject line and message body as necessary, and then click Send.

Send as an attachment

Excel, PowerPoint, Project, Publisher, Visio, and Word

  1. Click File > Share > Email, and then choose one of the following options:

    • Send as Attachment    Opens an email message with a copy of the file in its original file format attached.

    • Send as PDF    Opens an email message with a copy of the file in .pdf format attached.

    • Send as XPS    Opens an email message with a copy of the file in .xps format attached.

    • Send as Internet Fax    Opens a web page where you can choose from a list of providers that let you send a fax over the Internet.

      Note: The options you see will vary depending on the Office program you’re using.

  2. Enter the recipients’ aliases, edit the subject line and message body as necessary, and then click Send.

OneNote

  1. Click File > Send, and then choose one of the following options:

    • Send as Attachment    Opens an email message with both a copy of the file in its original file format and a copy of the file as a web page attached.

    • Send as PDF    Opens an email message with a copy of the file in .pdf format attached.

  2. Enter the recipients’ aliases, edit the subject line and message body as necessary, and then click Send.

Send as the body of an email message

If you are using Excel, Publisher, or Word, you can send your file as the actual email message content — not as an attachment. To do this, first you need to add the Send to Mail Recipient command to the Quick Access Toolbar. See Customize the Quick Access Toolbar to learn how to add commands.

  1. Open the file you want to send.

  2. In the Quick Access Toolbar, click Send to Mail Recipient to open an email message. Your file will appear in the body of the message.

  3. Enter the recipients’ aliases, edit the subject line and message body as necessary, and then click Send.

Send as an attachment

The following instructions apply to Excel, PowerPoint, Project, Publisher, Visio, and Word.

  1. Click File.

  2. Click Save & Send.

  3. Select Send Using E-mail, and then choose one of the following options:

    • Send as Attachment    Opens an email message with a copy of the file in its original file format attached.

    • Send as PDF    Opens an email message with a copy of the file in .pdf format attached.

    • Send as XPS    Opens an email message with a copy of the file in .xps format attached.

      Note: The PDF and XPS options are not available in Project 2010.

  4. Enter the recipients’ aliases, edit the subject line and message body as necessary, and then click Send.

The following instructions apply to OneNote 2010:

  1. Click File.

  2. Click Send, and then choose one of the following options:

    • E-mail Page as Attachment    Opens an email message with both a copy of the file in its original file format and a copy of the file as a web page attached.

    • E-mail Page as PDF   
      Opens an e-mail message with a copy of the file in .
      pdf
      format attached.

  3. Enter the recipients’ aliases, edit the subject line and message body as necessary, and then click Send.

Send as the body of an email message

If you are using Excel, Publisher, or Word, you can send your file as the actual email message content — not as an attachment. To do this, first you need to add the Send to Mail Recipient command to the Quick Access Toolbar. See Customize the Quick Access Toolbar to learn how to add commands.

To send your file as the body of an email message, follow these steps:

  1. Open the file you want to send.

  2. In the Quick Access Toolbar, click Send to Mail Recipient Send to Mail Recipient QAT Icon to open an email message. Your file will appear in the body of the message.

  3. Enter the recipients’ aliases, edit the subject line and message body as necessary, and then click Send.

See also

Attach files or insert pictures in Outlook email messages

Reduce the size of pictures and attachments

View, open, or save attachments

Need more help?

Want more options?

Explore subscription benefits, browse training courses, learn how to secure your device, and more.

Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.

Find solutions to common problems or get help from a support agent.

Distribution contacts list

Computers gave us incredible efficiency and flexibility. Nowadays, we write paper letters exclusively for the purpose of sending something special to the person we care about. Luckily, we do have tools which help us communicate with unprecedented speed. There is still room for improvement and greater efficiency. For instance, to improve the speed of email sending to a group of people one may also create distribution lists on Microsoft Outlook.

Distribution lists are groups of contacts which enable users to send the same email to multiple receivers simultaneously and in an automated way. Thus, you are able to inform the whole team or management of the company about something significant much faster than by filling all the To and CC fields. However, for this to happen, you have to first import contacts from Excel to outlook which are later transformed into the lists.

Contacts saves into Excel converting to Outlook

In this article, we will explain in detail how to import email addresses from Excel with the later purpose of creating lists and make your life easier. So if this is something you are looking for, stay tuned and wait for the detailed importing email addresses into outlook guide.

Guide On How To Smoothly Import Emails From Excel To Outlook

Spreadsheets account for a natural way for us to store contacts, emails and other types of information. They enable us to include many points and organize them in an easily comprehensible way. Therefore, people usually keep business contacts in spreadsheets. Outlook allows us to use all these data in combination with other apps through the import addresses into outlook function.

Below we offer you a simple way to add Excel email list to outlook in a detailed step-by-step algorithm of actions which is as follows:

  • prepare your Excel workbook format and properties: the very first and basic thing to do is to save Excel email address list as a .csv file. For this, choose the sheet you want to transfer, choose File and then Save As functions enabling you to select the needed format. Make sure to save it in the easily reachable place on your PC;
  • bring a spreadsheet to outlook contacts list: this part accounts for the majority of actions. Here, you start by choosing File > Open & Export > Import/Export functions on the ribbon. Upon doing so, choose “Import from another program or file” and proceed. Then, select the “Comma Separated Values” which is exactly the .csv format we have transformed the list in earlier. Finally, decide in which folder to put these data. It is usually the similarly-named folder worth choosing;
  • Map the spreadsheet columns with the respective fields: this has to be done to ensure the Outlook understands your data in the right way. Here you will need to do some manual mapping to ensure data compatibility.

Now, luckily, you have managed to import from Excel to outlook every single name, surname, and email address you need to use in your daily working routine. However, when it comes to efficiency, there is still one step left to do and it is to create the contact group out of these contacts. We are going to explain how it can be done in the next section.

Creating Special Lists

Obviously, there are many ways you will profit from executing Excel to outlook contacts transfer. We would like to suggest you only one out of the numerous ways to improve the efficiency of your daily email writing activities with the help of the contact groups. So, such is usually done in the following manner:

  • go to the Navigation Bar and click “People” icon or a word, depending on your bar configuration;
  • there choose “My Contacts” icon and select the folder where the contact group is to be saved;
  • select “New Contact Group” and give it a name which would satisfy your needs in the future to the greatest extent;
  • proceed by adding people from your contact list through the “Add Members” function. These will then appear in your newly created contact list;
  • save it and close the respective function.

Upon completing the mentioned above operations, you will get a chance to contact multiple people at the same time without any additional effort. To do so, simply type the name of the group into the To field and it will automatically drag all the contacts on the list. Thus, in just a few seconds your information will be shared with everyone in the group.

Sharing info in your contact group

Obviously, to be able to do so in a zip you have to first export emails to Excel, save these in the right .csv file format. Then, after an array of actions, finally, transfer these emails to the Outlook contacts group and only then use them in emails.

Contacts conversion instructions

  • How to convert Live Mail contacts to Outlook
  • Converting IncrediMail contacts to Outlook
  • Importing contacts from Thunderbird to Outlook

More Knowledge Base articles


Email conversion

Popular Email Conversion Methods, Tools and File types

Email conversion is an important part of any business or organization’s digital communication and digital marketing strategy which involves turning website visitors into leads. Email conversion is often done to…


eM Client

Transferring from IncrediMail to eM Client

At the beginning of 2020, there were many headlines about the IncrediMail shutdown of the desktop application for email correspondence. This took place on March 20, 2020. The closure left…


iCloud Contacts

How to Sync iCloud Contacts with Outlook

iCloud synchronizes your user data across your devices. It serves as a backup and allows easy sharing of photos, notes, videos, and other files with friends and family. If you…


MS Outlook

How to Print Emails and Attachments From Outlook

Users print emails from Microsoft Outlook for many reasons. The email may have a form that they want to print, fill out, and submit. Many people retain a physical copy…


PST file

Outlook PST File Size Limit: Figures and Consequences

MS Outlook is a useful software for handling email communications, keeping track of the personal schedule and important dates, storing contact information, as well as other essential information. Outlook uses…

Automate Outlook using vba: Sending Email from Excel using Outlook

————————————————————————————————

Contents:

Automate Outlook using vba

Send text and also contents from the host workbook’s worksheet range as Mail Body, and add an attachment with the mail, using Early Binding

Send the Host Workbook as an attachment with the mail, using Early Binding

Send multiple mails to ids sourced from the Host Workbook’s sheet, using Late Binding

Copy the Host Workbook, Add a New Sheet and Copy-Paste a Range to the Workbook copy, then send as an attachment with the mail, using Late Binding

Create a New Workbook, Add a New Sheet from the Host Workbook, send the new workbook as an attachment with the mail, using Late Binding

Find a mail item in the Inbox folder meeting a specified criteria, delete some or all its attachments, add a new attachment, forward it to a specific email id, and move the mail item to a newly created mail folder, using Late Binding

————————————————————————————————

In this section it is explained how to Send Emails from Excel using Outlook, using Automation in vba. Examples have been given to automate using both Early Binding and Late Binding.

When you use vba in an Office Application, say Outlook, a reference to the Outlook Object Library is set by default. When you Automate to work with Outlook objects from another application, say Excel, you can add a reference to the Outlook object library in Excel (your host application) by clicking Tools-References in VBE, which will enable using Outlook’s predefined constants. This is a must when you automate using Early Binding (explained earlier). Once this reference is added, a new instance of Outlook application can be created by using the New keyword.

Automate Outlook from Excel, using Late Binding: You need not add a reference to the Outlook object library in Excel (your host application), in this case you will not be able to use the Outlook’s predefined constants and will need to replace them by their numerical values in your code. In Late Binding, the object variable is declared as an Object Type which can be a reference to any object, and this makes an object late bound. In Late Binding, the object library is not exposed during design-time, but the binding happens during run-time using the CreateObject or the GetObject functions. CreateObject creates a new instance of Outlook and GetObject returns an already running instance of the Outlook object.

Click here for a detailed explanation of Automation using Early Binding and Late Binding.

Example 1: Send text and also contents from the host workbook’s worksheet range as Mail Body, and add an attachment with the mail, using Early Binding.

Sub OutlookMail_1()
‘Automate Sending Emails from Excel, using Outlook. Send text and also contents from the host workbook’s worksheet range as Mail Body, and add an attachment with the mail.
‘Automating using Early Binding: Add a reference to the Outlook Object Library in Excel (your host application) by clicking Tools-References in VBE, which will enable using Outlook’s predefined constants. Once this reference is added, a new instance of Outlook application can be created by using the New keyword.

‘variables declared as a specific object type ie. specific to the application which is being automated:
Dim applOL As Outlook.Application
Dim miOL As Outlook.MailItem
Dim recptOL As Outlook.Recipient
Dim ws As Worksheet

‘set worksheet:
Set ws = ThisWorkbook.Sheets(«Sheet1»)

‘Create a new instance of the Outlook application. Set the Application object as follows:
Set applOL = New Outlook.Application

‘create mail item:
Set miOL = applOL.CreateItem(olMailItem)

‘Add mail recipients, either the email id or their name in your address book. Invalid ids will result in code error.
Set recptOL = miOL.Recipients.Add(«info @globaliconnect.com»)
recptOL.Type = olTo
Set recptOL = miOL.Recipients.Add(«support @globaliconnect.com»)
recptOL.Type = olTo
Set recptOL = miOL.Recipients.Add(«John Kelly»)
recptOL.Type = olCC
Set recptOL = miOL.Recipients.Add(«Amit Tandon»)
recptOL.Type = olbcc

‘with the mail item:
With miOL

‘subject of the mail:
.Subject = «Financial Analysis — 2012»

‘Chr(10) represents line feed/new line, & Chr(13) represents carriage return. Send text and also contents from the host workbook’s worksheet range as Mail Body.
.Body = «Hi Chris,» & Chr(10) & Chr(10) & «Enclosing the financial analysis.» & Chr(10) & Chr(10) & Trim(ws.Range(«A1»)) & Trim(ws.Range(«A2»)) & Chr(10) & Chr(10) & Trim(ws.Range(«A3»)) & Chr(10) & Chr(10) & «Best Regards,» & Chr(10) & «John Pollard»

‘set importance level for the mail:
.Importance = olImportanceHigh
‘add an attachment to the mail:
.Attachments.Add («C:UsersAmit TandonDocumentsAnalysis.docx»)
‘send the mail:

.send

End With

‘clear the object variables:
Set applOL = Nothing
Set miOL = Nothing
Set recptOL = Nothing

End Sub

Example 2: Send the Host Workbook as an attachment with the mail, using Early Binding.

Sub OutlookMail_2()
‘Automate Sending Emails from Excel, using Outlook. Send the Host Workbook as an attachment with the mail.
‘Automating using Early Binding: Add a reference to the Outlook Object Library in Excel (your host application) by clicking Tools-References in VBE, which will enable using Outlook’s predefined constants. Once this reference is added, a new instance of Outlook application can be created by using the New keyword.

‘variables declared as a specific object type ie. specific to the application which is being automated:
Dim applOL As Outlook.Application
Dim miOL As Outlook.MailItem

‘Create a new instance of the Outlook application. Set the Application object as follows:
Set applOL = New Outlook.Application
‘create mail item:
Set miOL = applOL.CreateItem(olMailItem)

With miOL

.To = «info @globaliconnect.com»
.CC = «»
.Importance = olImportanceLow
.Subject = «Mail Automation»
.Body = «Sending the Active Excel Workbook as attachment!»
‘add host workbook as an attachment to the mail:
.Attachments.Add ActiveWorkbook.FullName
.ReadReceiptRequested = True

.send

End With

‘clear the object variables:
Set applOL = Nothing
Set miOL = Nothing

End Sub

Example 3: Send multiple mails to ids sourced from the Host Workbook’s sheet, using Late Binding.

For live code of this example, click to download excel file.

Sub OutlookMail_3()
‘Automate Sending Emails from Excel, using Outlook. Send multiple mails to ids sourced from the Host Workbook’s sheet.
‘Automating Outlook from Excel, using Late Binding. You need not add a reference to the Outlook object library in Excel (your host application), in this case you will not be able to use the Outlook’s predefined constants and will need to replace them by their numerical values in your code.

‘variables declared as Object Type, which can be a reference to any object:
Dim oApplOL As Object
Dim oMiOL As Object
Dim lastRow As Long
Dim ws As Worksheet
Dim strMailSubject As String
Dim strMailMessage As String

‘set worksheet:
Set ws = ActiveWorkbook.Sheets(«Sheet1»)

‘Email ids are entered in column A of Sheet5 — determine last data row in column A of the worksheet:
lastRow = ws.Cells(Rows.Count, «A»).End(xlUp).Row

‘Create a new instance of the Outlook application, if an existing Outlook object is not available.
‘Set the Application object as follows:
On Error Resume Next
Set oApplOL = GetObject(, «Outlook.Application»)
‘if an instance of an existing Outlook object is not available, an error will occur (Err.Number = 0 means no error):
If Err.Number <> 0 Then

Set oApplOL = CreateObject(«Outlook.Application»)

End If
‘disable error handling:
On Error GoTo 0
‘ignores an invalid mail id syntax, and code execution will resume
On Error Resume Next

‘loop through all cells in column A:

For i = 1 To lastRow

‘validate mail syntax:
‘Like operator in vba: If the string satisfies the specified pattern, it will return True. * denotes zero or more characters, ? denotes a single character.
‘The following statement returns True if the string has an «@» and atleast one character before it, and atleast one character after it, then followed by «.» and atleast one character after it.

If Trim(ws.Cells(i, 1).Value) Like «*?@?*.?*» Then

‘pick mail subject from Range(«C1»):

strMailSubject = ws.Cells(1, 3)

‘Add text to mail message and also pick text from Range(«C2») and Range(«C3»):

strMailMessage = «Hello « & ws.Cells(i, 2) & vbCrLf & vbCrLf & ws.Cells(3, 3) & vbCrLf & vbCrLf & «Best Regards,» & Chr(13) & «Administrator»

‘create mail item:

‘Built-in constant olMailItem has been replaced by its value 0.

Set oMiOL = oApplOL.CreateItem(0)

With oMiOL

‘pick mails ids from column A:
.To = ws.Cells(i, 1)
‘Built-in constant olImportanceLow has been replaced by its value 0.
.Importance = 0
.Subject = strMailSubject
.Body = strMailMessage
.ReadReceiptRequested = False

.send

End With

End If

‘set a 2 seconds time interval:
Application.Wait (Now + TimeValue(«0:00:02»))

Next i

‘clear the object variables:
Set oApplOL = Nothing
Set oMiOL = Nothing

End Sub

Example 4: Copy the Host Workbook, Add a New Sheet and Copy-Paste a Range to the Workbook copy, then send as an attachment with the mail, using Late Binding.

For live code of this example, click to download excel file.

Sub OutlookMail_4()
‘Automate Sending Emails from Excel, using Outlook. Copy the Host Workbook, Add a New Sheet and Copy-Paste a Range to the Workbook copy, then send as an attachment with the mail.
‘Automating Outlook from Excel, using Late Binding. You need not add a reference to the Outlook object library in Excel (your host application), in this case you will not be able to use the Outlook’s predefined constants and will need to replace them by their numerical values in your code.

‘variables declared as Object Type, which can be a reference to any object:
Dim oApplOL As Object
Dim oMiOL As Object
Dim oRecptOL As Object
Dim wb As Workbook
Dim wsNewSheet As Worksheet
Dim strWbName As String
Dim strWbPath As String

‘Application.ScreenUpdating Property. If set to False, screen updating will be turned off, and you will not be able to view what your code does but it executes faster. It is common to turn off screen updating in vba procedures to make codes run faster.
Application.ScreenUpdating = False

‘Create a new instance of the Outlook application, if an existing Outlook object is not available.
‘Set the Application object as follows:
On Error Resume Next
Set oApplOL = GetObject(, «Outlook.Application»)
‘if an instance of an existing Outlook object is not available, an error will occur (Err.Number = 0 means no error):
If Err.Number <> 0 Then

Set oApplOL = CreateObject(«Outlook.Application»)

End If
‘disable error handling:
On Error GoTo 0

‘set name for the Workbook copy, which is same as the host workbook preceded with «Copy of»:
strWbName = «Copy of « & ThisWorkbook.Name
‘set path where to save the Workbook copy, to the same location as the host workbook:
strWbPath = ThisWorkbook.Path

‘create the Workbook copy with the name and in the location set above:
ActiveWorkbook.SaveCopyAs strWbPath & «» & strWbName

‘set object variable for the opened Workbook copy:
Set wb = Workbooks.Open(strWbPath & «» & strWbName)

‘confirm if you want to add a new sheet as a cover sheet in the Workbook copy:
If MsgBox(«Want to add a cover sheet in the new workbook?», vbYesNo + vbQuestion, «Cover sheet?») = vbYes Then

‘add the new sheet as the first sheet in the Workbook copy:
Set wsNewSheet = wb.Sheets.Add(Before:=Sheets(1), Count:=1, Type:=xlWorksheet)
‘name the new sheet:
wsNewSheet.Name = «CoverSheet»
‘Copy-Paste from host workbook to the new cover sheet in the Workbook copy:
ThisWorkbook.Sheets(«Sheet1»).

Range(«A1:A2»).Copy
wsNewSheet.Range(«E15:E16»).PasteSpecial Paste:=xlValues
wsNewSheet.Range(«E1»).Value = «Cover Sheet»

End If

‘save the Workbook copy:
wb.Save
‘create mail item:
‘Built-in constant olMailItem has been replaced by its value 0.
Set oMiOL = oApplOL.CreateItem(0)

‘add mail recipients:
Set oRecptOL = oMiOL.Recipients.Add(«info @globaliconnect.com»)
‘Built-in constant olTo has been replaced by its value 1.
oRecptOL.Type = 1

With oMiOL

‘Built-in constant olImportanceLow has been replaced by its value 0.
.Importance = 0
.Subject = «Mail Automation»
.Body = «Sending a Copy of the Active Excel Workbook, with a New Added Sheet and Range Copied, as attachment!»
‘attach the Workbook copy in the mail item:
.Attachments.Add wb.FullName
.ReadReceiptRequested = True

.send

End With

‘close the Workbook copy after saving:

wb.Close savechanges:=True

Application.ScreenUpdating = True

‘clear the object variables:
Set oApplOL = Nothing
Set oMiOL = Nothing
Set oRecptOL = Nothing

End Sub

Example 5: Create a New Workbook, Add a New Sheet from the Host Workbook, send the new workbook as an attachment with the mail, using Late Binding.

For live code of this example, click to download excel file.

Sub OutlookMail_5()
‘Automate Sending Emails from Excel, using Outlook. Create a New Workbook, Add a New Sheet from the Host Workbook, send the new workbook as an attachment with the mail.
‘Automating Outlook from Excel, using Late Binding. You need not add a reference to the Outlook object library in Excel (your host application), in this case you will not be able to use the Outlook’s predefined constants and will need to replace them by their numerical values in your code.

‘variables declared as Object Type, which can be a reference to any object:
Dim oApplOL As Object
Dim oMiOL As Object
Dim oRecptOL As Object
Dim wbHost As Workbook
Dim wb As Workbook
Dim wsNewSheet As Worksheet
Dim strWbName As String
Dim strWbPath As String
Dim strFileExtn As String
Dim lFileFrmt As Long

‘Application.ScreenUpdating Property. If set to False, screen updating will be turned off, and you will not be able to view what your code does but it executes faster. It is common to turn off screen updating in vba procedures to make codes run faster.
Application.ScreenUpdating = False

‘Create a new instance of the Outlook application, if an existing Outlook object is not available.
‘Set the Application object as follows:
On Error Resume Next
Set oApplOL = GetObject(, «Outlook.Application»)
‘if an instance of an existing Outlook object is not available, an error will occur (Err.Number = 0 means no error):
If Err.Number <> 0 Then

Set oApplOL = CreateObject(«Outlook.Application»)

End If
‘disable error handling:
On Error GoTo 0

Set wbHost = ActiveWorkbook

‘Choose the excel File Type & Format for the new workbook:
‘It is advisable to use values in lieu of built-in constants, so that the code runs across all office / excel versions: xlWorkbookNormal = -4143; xlExcel8 = 56; xlOpenXMLWorkbook = 51; xlOpenXMLWorkbookMacroEnabled = 52; xlExcel12 = 50.
‘Built-in constants have been replaced by their values below.

If MsgBox(«Save as .xls file (97-2003 format) if you are using Excel 97-2003?», vbYesNo + vbQuestion, «Excel File Format») = vbYes Then

‘note that you can work with macros in this file format:
strFileExtn = «.xls»
lFileFrmt = -4143

ElseIf MsgBox(«Save as .xls file (97-2003 format) even though you are using Excel 2007?», vbYesNo + vbQuestion, «Excel File Format») = vbYes Then

‘note that you can work with macros in this file format:

strFileExtn = «.xls»

lFileFrmt = 56

ElseIf MsgBox(«Save as .xlsx file (2007 format — without macros) if you are using Excel 2007?», vbYesNo + vbQuestion, «Excel File Format») = vbYes Then

‘note that you cannot save macros while using this file format:

strFileExtn = «.xlsx»

lFileFrmt = 51

ElseIf MsgBox(«Save as .xlsm file (2007 format — macros enabled) if you are using Excel 2007?», vbYesNo + vbQuestion, «Excel File Format») = vbYes Then

strFileExtn = «.xlsm»

lFileFrmt = 52

ElseIf MsgBox(«Save as .xlsb file (2007 format, Excel Binary Workbook — macros enabled) if you are using Excel 2007?», vbYesNo + vbQuestion, «Excel File Format») = vbYes Then

strFileExtn = «.xlsb»

lFileFrmt = 50

Else

Exit Sub

End If

‘set path where to save the New Workbook, to the same location as the host workbook:
strWbPath = ThisWorkbook.Path
‘set name for the New Workbook with the defined path and the file extension as determined above:
strWbName = strWbPath & «» & «NewWorkbook» & strFileExtn

‘add new workbook:
Set wb = Workbooks.Add
‘save the new workbook with its name, file format and password:
wb.SaveAs fileName:=strWbName, FileFormat:=lFileFrmt, Password:=«123», ReadOnlyRecommended:=False

‘copy sheet from host workbook to new workbook, at the end:
wbHost.Sheets(«Sheet2»).Copy After:=wb.Sheets(wb.Sheets.Count)

‘save the new workbook:
wb.Save

‘create mail item:
‘Built-in constant olMailItem has been replaced by its value 0.
Set oMiOL = oApplOL.CreateItem(0)
‘add mail recipients:
Set oRecptOL = oMiOL.Recipients.Add(«info @globaliconnect.com»)
‘Built-in constant olTo has been replaced by its value 1.
oRecptOL.Type = 1

With oMiOL

‘Built-in constant olImportanceNormal has been replaced by its value 1.

.Importance = 1
.Subject = «Mail Automation»
.Body = «Sending a New Excel Workbook, after Adding a Sheet, as attachment!»
‘send new workbook as attachment to the mail:
.Attachments.Add wb.FullName
.ReadReceiptRequested = False

.send

End With

‘close new workbook after mail is sent:
wb.Close

Application.ScreenUpdating = True

‘clear the object variables:
Set oApplOL = Nothing
Set oMiOL = Nothing
Set oRecptOL = Nothing

End Sub

Example 6: Find a mail item in the Inbox folder meeting a specified criteria, delete some or all its attachments, add a new attachment, forward it to a specific email id, and move the mail item to a newly created mail folder, using Late Binding.

Sub OutlookMail_6()
‘Automate Sending Emails from Excel, using Outlook. Find a mail item in the Inbox folder meeting a specified criteria, delete some or all its attachments, add a new attachment, forward it to a specific email id, and move the mail item to a newly created mail folder.
‘Automate Outlook from Excel, using Late Binding. You need not add a reference to the Outlook object library in Excel (your host application), in this case you will not be able to use the Outlook’s predefined constants and will need to replace them by their numerical values in your code.

‘variables declared as Object Type, which can be a reference to any object:
Dim oApplOL As Object
Dim oNsOL As Object
Dim oMFolder As Object
Dim oPFolder As Object
Dim oNFolder As Object
Dim oMItems As Object
Dim oMItem As Object
Dim oMItemF As Object
Dim oAtt As Object
Dim oAtts As Object
Dim i As Long, n As Long

‘Create a new instance of the Outlook application, if an existing Outlook object is not available.
‘Set the Application object as follows:
On Error Resume Next
Set oApplOL = GetObject(, «Outlook.Application»)
‘if an instance of an existing Outlook object is not available, an error will occur (Err.Number = 0 means no error):
If Err.Number <> 0 Then

Set oApplOL = CreateObject(«Outlook.Application»)

End If
‘disable error handling:
On Error GoTo 0

‘use the GetNameSpace method to instantiate (ie. create an instance of) a NameSpace object variable, to access existing Outlook items. Set the NameSpace object as follows:
Set oNsOL = oApplOL.GetNamespace(«MAPI»)

‘assign the object variable oPFolder to the «Personal Folders» folder:
Set oPFolder = oNsOL.Folders(«Personal Folders»)
‘A new folder is being created to which the forwarded mails will be moved. Use the Folders.Add Method to create a new folder «New Folder 1» in the «Personal Folders» folder:
Set oNFolder = oPFolder.Folders.Add(«New Folder 1»)

‘Assign the object variable oMFolder to the default Inbox folder. Built-in constant olFolderInbox has been replaced by its value 6.
Set oMFolder = oNsOL.GetDefaultFolder(6)
‘To assign the object variable oMFolder to the default sent items folder. Built-in constant olFolderSentMail has been replaced by its value 5.
‘Set oMFolder = oNsOL.GetDefaultFolder(5)
‘set the items collection:
Set oMItems = oMFolder.Items

‘search mails in Inbox folder whose Importance is set to High:
Set oMItem = oMItems.Find(«[Importance]=«»High»»»)
‘to search mail items per sender’s name:
‘Set oMItem = oMItems.Find(«[SenderName] = ‘James Bond’«)
‘to search mails which have no subject:
‘Set oMItem = oMItems.Find(«[Subject]=«»»»»)

‘loop through all mails in the folder:

For i = 1 To oMItems.Count

‘Check if mail item (of High Importance) is not found. TypeName function returns the data type information of a variable ex. MailItem. If the function returns «Nothing», it means that no object is currently assigned to the variable.

If TypeName(oMItem) = «Nothing» Then

MsgBox «No more mail whose Importance is set to High!»
MsgBox «Total Mails found whose Importance is set to High: » & i — 1

Exit Sub

End If

‘search result no. of the mail item being referenced:
MsgBox «Search Result No: » & i
‘received time of the High Importance mail:
MsgBox «Received Time: » & oMItem.ReceivedTime
‘sender’s name of the High Importance mail:
MsgBox «Sender’s Name: » & oMItem.SenderName
‘use the Forward method to Forward a mail item, wherein a copy of the mail item is returned as a new object, which is set as oMItemF:
Set oMItemF = oMItem.Forward()

With oMItemF

.Display
.To = «info @globaliconnect.com»
.CC = «»
‘Built-in constant olImportanceLow has been replaced by its value 0.
.Importance = 0
.Subject = .Subject & » — Forwarding Mail!»

‘confirm each attachment in the forwarded mail (oMItemF) for deletion:
Set oAtts = .Attachments

For n = oAtts.Count To 1 Step -1

If MsgBox(«Want to Delete Attachment: » & oAtts(n).DisplayName, vbYesNo + vbQuestion, «Delete Attachment?») = vbYes Then

oAtts(n).Delete

End If

Next n

‘add your own attachment to the forwarded mail, oMItemF:
.Attachments.Add («C:UsersAmit TandonDocumentsFriends.docx»)
.ReadReceiptRequested = False
‘move forwarded mail to a new folder:
.Move oNFolder

.send

End With

‘search next mail item whose Importance is set to High:
Set oMItem = oMItems.FindNext

Next i

‘clear the object variables:
Set oApplOL = Nothing
Set oNsOL = Nothing
Set oMFolder = Nothing
Set oPFolder = Nothing
Set oNFolder = Nothing
Set oMItems = Nothing
Set oMItem = Nothing
Set oMItemF = Nothing
Set oAtt = Nothing
Set oAtts = Nothing

End Sub

Return to VBA Code Examples

This tutorial will show you how to send emails from Excel through Outlook using VBA.

Sending the Active Workbook

Function SendActiveWorkbook(strTo As String, strSubject As String, Optional strCC As String, Optional strBody As String) As Boolean
   On Error Resume Next
   Dim appOutlook As Object
   Dim mItem As Object
'create a new instance of Outlook
   Set appOutlook = CreateObject("Outlook.Application")
   Set mItem = appOutlook .CreateItem(0)
   With mItem 
     .To = strTo
     .CC = ""
     .Subject = strSubject
     .Body = strBody
     .Attachments.Add ActiveWorkbook.FullName
'use send to send immediately or display to show on the screen
    .Display 'or .Send
   End With
'clean up objects
  Set mItem = Nothing
  Set appOutlook = Nothing
End Function

The function above can be called using the procedure below

Sub SendMail()
   Dim strTo As String
   Dim strSubject As String
   Dim strBody As String
'populate variables
   strTo = "jon.smith@gmail.com"
   strSubject = "Please find finance file attached"
   strBody = "some text goes here for the body of the email"
'call the function to send the email
   If SendActiveWorkbook(strTo, strSubject, , strBody) = true then
      Msgbox "Email creation Success"
   Else
      Msgbox "Email creation failed!"
   End if
End Sub

vba outlook email

Using Early Binding to refer to the Outlook Object Library

The code above uses Late Binding to refer to the Outlook Object. You can add a reference to Excel VBA, and declare the Outlook application and Outlook Mail Item using Early Binding if preferred. Early Binding makes the code run faster, but limits you as the user would need to have the same version of Microsoft Office on their PC.

Click on the Tools menu and References to show the reference dialog box.

vba outlook add reference

Add a reference to the Microsoft Outlook Object Library for the version of Office that you are using.

vba outlook references

You can then amend your code to use these references directly.

vba outlook early binding

A great advantage of early binding is the drop down lists that show you the objects that are available to use!

Sending a Single Sheet from the Active Workbook

To send a single sheet, you first need to create a new workbook from the existing workbook with just that sheet in it, and then send that sheet.

Function SendActiveWorksheet(strTo As String, strSubject As String, Optional strCC As String, Optional strBody As String) As Boolean
   On Error GoTo eh
'declare variables to hold the objects required
   Dim wbDestination As Workbook
   Dim strDestName As String
   Dim wbSource As Workbook
   Dim wsSource As Worksheet
   Dim OutApp As Object
   Dim OutMail As Object
   Dim strTempName As String
   Dim strTempPath As String
'first create destination workbook
   Set wbDestination = Workbooks.Add
   strDestName = wbDestination.Name
'set the source workbook and sheet
   Set wbSource = ActiveWorkbook
   Set wsSource = wbSource.ActiveSheet
'copy the activesheet to the new workbook
   wsSource.Copy After:=Workbooks(strDestName).Sheets(1)
'save with a temp name
   strTempPath = Environ$("temp") & ""
   strTempName = "List obtained from " & wbSource.Name & ".xlsx"
   With wbDestination
      .SaveAs strTempPath & strTempName
'now email the destination workbook
      Set OutApp = CreateObject("Outlook.Application")
      Set OutMail = OutApp.CreateItem(0)
      With OutMail
         .To = strTo
         .Subject = strSubject
         .Body = strBody
         .Attachments.Add wbDestination.FullName
'use send to send immediately or display to show on the screen
         .Display 'or .Display
      End With
      .Close False
  End With
'delete temp workbook that you have attached to your mail
   Kill strTempPath & strTempName
'clean up the objects to release the memory
   Set wbDestination = Nothing
   Set wbSource = Nothing
   Set wsSource = Nothing
   Set OutMail = Nothing
   Set OutApp = Nothing
Exit Function
eh:
   MsgBox Err.Description
End Function

and to run this function, we can create the following procedure

Sub SendSheetMail()
   Dim strTo As String
   Dim strSubject As String
   Dim strBody As String
   strTo = "jon.smith@gmail.com"
   strSubject = "Please find finance file attached"
   strBody = "some text goes here for the body of the email"
   If SendActiveWorksheet(strTo, strSubject, , strBody) = True Then
      MsgBox "Email creation Success"
   Else
      MsgBox "Email creation failed!"
   End If
End Sub

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

Зачастую базы данных e-mail адресов электронной почты либо ведутся в приложении Excel, либо экспортируются в Excel-файл из других источников, поэтому для многих пользователей актуальным становится вопрос рассылки писем на основе данных, содержащихся в Excel-файлах.

Стандартные возможности Excel ограничиваются отправкой активной рабочей книги по электронной почте (Кнопка Office/Отправить/Электронная почта), в то время как возможности Visual Basic for Application предоставляют пользователям Excel и Outlook практически неограниченные возможности. Существует множество различных способов отправки электронной почты прямо из приложения Excel, как при помощи почтовых клиентов, таких как Outlook или The Bat, так и без их использования. В этой статье речь пойдет об отправке почты из Excel при помощи почтовой программы Outlook. 

Отправка писем макросом

Отправка писем, информация для которых содержится в файлах Excel, может быть реализована различными способами, при помощи макроса, написанного для Excel, который вызывает приложение Outlook и отправляет через него письма, при помощи макроса, написанного для Outlook, который вызывает приложение Excel и берет данные для писем из Excel-файла, или же смешанным способом, когда используются процедуры и функции как в одном, так и в другом приложении. По ссылкам приведены примеры простейших макросов по отправке электронных писем для Excel и для Outlook.

Готовая надстройка для Excel по рассылке электронных писем, созданная на основе макроса, сочетает в себе широкие возможности VBA и простоту в использовании. Ниже представлено диалоговое окно надстройки.

kak otpravit pisma iz excel

При помощи полей, расположенных в левой части диалогового окна можно выбрать способ рассылки и задать диапазоны ячеек, данные из которых будут использоваться при формировании электронных писем. Опции правой части диалогового окна позволяют использовать дополнительные параметры, например, подставлять имена получателей в темы и/или тексты писем, отправлять html-файл в теле письма либо использовать стандартную подпись Outlook, которая также представляет собой html-файл. Кроме того разными почтовыми сервисами используются различные ограничения на отправку писем по размеру, по количеству, по скорости отправки и так далее (рекомендуется ознакомиться с ними заранее), и для того чтобы не выходить за рамки этих ограничений, в надстройке предусмотрена опция «Использовать задержку между письмами», которая позволяет настроить паузу между отправкой писем.

Возможности надстройки

С этой надстройкой Вы сможете:

1. Отправлять на разные адреса электронной почты письма одинакового содержания и с одной темой;

* в ячейке для адреса получателя может быть указано несколько адресов электронной почты без пробелов, через знак-разделитель «;»  (при этом получатель письма будет видеть все эти адреса). 

2. отправлять на разные адреса электронной почты индивидуальные письма со своим содержанием и разными темами;

3. формировать электронные письма из Excel-таблиц путем выделения диапазонов, содержащих необходимую информацию; 

4. создавать персональные электронные письма, используя имена получателей в темах и/или в тексте писем (при выборе опций, использующих имена адресатов, поле для выбора диапазона с именами становится активным);

5. устанавливать паузу между отправкой писем;

6. вставлять html-файл в тело письма либо добавлять к тексту письма стандартную подпись, созданную в Outlook;

7. добавлять изображения (картинки) к письму, созданному на основе html-файла;

8. добавлять во вложения к письмам одинаковый набор файлов;

9. добавлять к каждому письму отдельное вложение;

10. отправлять письма из разных аккаунтов, используемых в Microsoft Outlook;

11. форматировать отправляемый текст при помощи html-тэгов прямо в ячейках;

12. создавать электронные письма, но не отправлять их автоматически, а сохранять в черновики для проверки, корректировки и последующего отправления вручную;

13. одним кликом мыши вызывать диалоговое окно макроса прямо из панели инструментов Excel.

rassylka pisem iz Excel cherez Outlook

CompleteSolutionнадстройка для рассылки писем из Excel через Microsoft Outlook

Внимание! При автоматизированной рассылке писем необходимо помнить о том, что:

1. При отправке сообщений при помощи макросов и надстроек может появляться окно подтверждения отправки для каждого письма (о том как избавиться от этого окна можно прочитать отдельно);

2. в некоторых почтовых сервисах, как платных так и бесплатных, действуют различные ограничения на отправку писем, например по количеству отправляемых писем в час или в сутки, по максимальному размеру отправляемых писем, по количеству писем, отправленных на несуществующие адреса и так далее. При несоблюдении таких ограничений Ваш почтовый ящик может быть заблокирован;

3. при использовании паузы между отправкой писем в этой надстройке, Excel будет заблокирован до полного окончания отправки писем.

Видео по работе с надстройкой

Как отправить письма с разных адресов?

В приложении Outlook может быть настроено несколько учетных записей, при этом отправка писем ведется с того адреса, который используется по умолчанию. Если необходимо сделать так, чтобы рассылка велась с другого адреса, можно написать этот адрес в ячейках столбца на листе Excel и в поле «Учетные записи» диалогового окна надстройки выделить эти ячейки. Более того, можно отправлять письма с разных аккаунтов (все они должны быть настроены в Outlook). Для этого на рабочем листе Excel создается список учетных записей, с которых будет вестись рассылка и диапазон ячеек этого списка указывается в поле «Учетные записи». rassylka pisem s raznyh uchetnyh zapisej

Как добавить вложения к письмам?

В надстройке реализовано два разных способа добавления вложений к отправляемым письмам. Установка флажка в поле «Добавить файлы во вложение» позволяет прицепить несколько файлов, при этом выбранный набор файлов будет прикреплен к каждому письму почтовой рассылки. Можно прикрепить индивидуальное вложение к каждому письму, в таком случае используется поле «Вложения», а на рабочем листе для каждого адресата прописывается полный путь к файлу. Этим способом можно вложить только по одному файлу в каждое письмо. Также можно комбинировать описанные выше способы отправки вложений, то есть уникальный файл вложить при помощи поля «Вложения», а одинаковые для всех файлы вложить при помощи установки флажка в поле «Добавить файлы во вложение». Может возникнуть необходимость отправки нескольких персональных файлов каждому адресату. В таком случае необходимо для каждого письма создавать индивидуальные архивы и отправлять их через поле «Вложения». Создание архивов можно выполнять программно, в автоматическом режиме.

Как вставить картинку в письмо?

При рассылке электронных писем с помощью надстройки, предусмотрена возможность добавления к письму изображений. При этом изображения можно прикрепить к письму, как обычные вложения, а можно вставить в тело письма.

1. Для отправки картинок обычными вложенными файлами достаточно просто установить флажок в поле «Добавить файлы во вложение» и при помощи кнопки обзора выбрать необходимые файлы, не зависимо от того используется html-файл или нет;

2. Чтобы вставить картинку в тело письма, необходимо использовать html-файл. Картинку предварительно нужно выложить в сеть интернет, чтобы она была доступна получателям писем, поместив ее на сервер любого файлобменника, например на www.imageup.ru (либо другой сервис, предоставляющий прямые ссылки). В свою очередь в html-файле достаточно в нужном месте вставить ссылку на эту картинку, а также указать размеры картинки, при этом если ссылка указана правильно, получатель письма должен увидеть изображение в теле письма. Ссылка должна иметь вид:

<img src=’http://macros-vba.ru/files/Logo.png’ height=39 width=165>  если изображение размещено на сайте, или

<img src=’http://www.imageup.ru/img67/2780968/123123.jpg’ height=39 width=165> если изображение размещено на сервере файлобменника (адрес картинки сгенерирован файлобменником).

Создать html-файл можно при помощи текстового редактора Word, для этого при сохранении файла необходимо выбрать тип файла «Веб-страница (*.htm; *.html)». После сохранения файла, его необходимо открыть при помощи блокнота или текстового редактора NotePad++, вставить в нужное место документа ссылку на картинку, после чего сохранить внесенные изменения.

Как отправить письмом отформатированный текст?

Механизм, используемый для автоматической рассылки писем, позволяет отправлять только неотформатированный текст, то есть, если в ячейках Excel для рассылки приготовлен текст, имеющий переносы строк, измененные цвета и размеры шрифтов, отступы и так далее, то при автоматическом формировании писем все эти настройки формата текста игнорируются. Тем не менее, осуществить отправку отформатированного текста все-таки можно, для этого в тексте писем достаточно использовать html-тэги, например, для переноса строки — тэг br, заключенный в угловые скобки <>, а для того чтобы сделать текст жирным — тэги b и /b, также в угловых скобках каждый. Разобраться достаточно просто.

Как совместить текст из ячеек с текстом html-файла?

При помощи html-тэгов можно решить и более сложную задачу. Предположим, необходимо сделать рассылку отформатированного определенным образом текста в html-файле, обратившись при этом к адресатам по именам. Часть текста при этом содержится в ячейках на рабочем листе, другая часть в html-файле. При помощи html-тэгов в ячейках рабочего листа и подбора параметров шрифта в html-файле можно добиться одинакового отображения текста.

html tegi v tekste pisem

Для решения этой задачи удобнее предварительно объединить имена адресатов с текстом письма при помощи текстовой функции «СЦЕПИТЬ», сохранить результат преобразования в виде значений и уже после этого добавлять необходимые html-тэги. В примере на изображении показано как при помощи тэгов осуществить выравнивание текста по центру, задать курсив, название, размер и цвет шрифта. Образцы файлов прилагаются. После того как все необходимые тэги сформированы в одной ячейке, их можно быстро подставить в начале и в конце значений остальных ячеек столбца. Поможет в этом надстройка для подстановки символов и значений.

Каким образом можно письма сформировать, но не отправлять?

При установке флажка в поле «Создать, но не отправлять» сформированные письма не отправляются автоматически, а сохраняются в папку «Черновики», предоставляя возможность произвести проверку, при необходимости внести изменения и отправить проверенные почтовые сообщения в ручном режиме.

Другие материалы по теме:

Пример макроса, отправляющего письма со вложениями из Excel через почтовый клиент Outlook:

Sub Отправить_Письмо_из_Outlook()

‘отправляем письмо без вложений

res = SendEmailUsingOutlook(«name@domain.ru», «Текст письма 1», «Тема письма 1»)

If res Then Debug.Print «Письмо 1 отправлено успешно» Else Debug.Print «Ошибка отправки»

‘отправляем письмо с 1 вложением

attach$ = ThisWorkbook.FullName ‘ прикрепляем текущий файл Excel

res = SendEmailUsingOutlook(«name@domain.ru», «Текст письма 2», «Тема письма 2», attach$)

If res Then Debug.Print «Письмо 2 отправлено успешно» Else Debug.Print «Ошибка отправки»

‘отправляем письмо с несколькими вложениями

Dim coll As New Collection ‘ заносим в коллекцию список прикрепляемых файлов

coll.Add «C:Documents and SettingsAdminРабочий столTyres.jpg»

coll.Add «C:Documents and SettingsAdminРабочий столcalc.xls»

coll.Add ThisWorkbook.FullName ‘ прикрепляем текущий файл Excel

res = SendEmailUsingOutlook(«name@domain.ru», «Текст письма 3», «Тема письма 3», coll)

If res Then Debug.Print «Письмо 3 отправлено успешно» Else Debug.Print «Ошибка отправки»

End Sub

Макрос использует функцию SendEmailUsingOutlook, которая:

  • принимает в качестве параметров адрес получателя письма, тему и текст письма, список вложений
  • запускает Outlook, формирует письмо, и отправляет его
  • возвращает TRUE, если отправка прошла успешно, или FALSE, если с отправкой почты вызникли проблемы

Код функции SendEmailUsingOutlook:

Function SendEmailUsingOutlook(ByVal Email$, ByVal MailText$, Optional ByVal Subject$ = «», _

Optional ByVal AttachFilename As Variant) As Boolean

‘ функция производит отправку письма с заданной темой и текстом на адрес Email

‘ с почтового ящика, настроенного в Outlook для отправки писем «по-умолчанию»

‘ Если задан параметр AttachFilename, к отправляемому письму прикрепляется файл (файлы)

On Error Resume Next: Err.Clear

Dim OA As Object: Set OA = CreateObject(«Outlook.Application»)

If OA Is Nothing Then MsgBox «Не удалось запустить OUTLOOK для отправки почты», vbCritical: Exit Function

With OA.CreateItem(0) ‘создаем новое сообщение

.To = Email$: .Subject = Subject$: .Body = MailText$

If VarType(AttachFilename) = vbString Then .Attachments.Add AttachFilename

If VarType(AttachFilename) = vbObject Then ‘ AttachFilename as Collection

For Each file In AttachFilename: .Attachments.Add file: Next

End If

For i = 1 To 100000: DoEvents: Next ‘ без паузы не отправляются письма без вложений

Err.Clear: .Send

SendEmailUsingOutlook = Err = 0

End With

Set OutApp = Nothing

End Function

Пример макроса, с получением параметров письма из ячеек листа Excel: 

Sub Отправить_Письмо_из_Outlook()

‘ адрес получателя — в ячейке A1, текст письма — в ячейке A2

res = SendEmailUsingOutlook(Cells(1, 1), Range(«a2»), «Тема письма 1»)

If res Then Debug.Print «Письмо 1 отправлено успешно» Else Debug.Print «Ошибка отправки»

End Sub

Like this post? Please share to your friends:
  • Make a sentence with the word break
  • Mail button in word
  • Mail and merge in word
  • Make a sentence with the word badly
  • Maicraft office word 2016 скачать бесплатно