What is cdo excel

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

  1. Click File > Share > Email, and then choose one of the following options:
  2. Enter the recipients’ aliases, edit the subject line and message body as necessary, and then click Send.

Contents

  • 1 Can Excel send emails automatically?
  • 2 How do I send a mass email from an Excel spreadsheet?
  • 3 How can I send email from Excel without Outlook?
  • 4 How do I create a mail merge from Excel?
  • 5 How do I send an email from Excel to Gmail?
  • 6 Can you mail merge without Outlook?
  • 7 How do you do a mail merge in Excel without word?
  • 8 Can an Excel spreadsheet be used as the data source for a Word mail merge yes or no?
  • 9 Can you make Avery labels from an Excel spreadsheet?
  • 10 How do I mail merge from Excel to Outlook?
  • 11 How do I mail merge from Excel to Word labels?
  • 12 What are the six steps of mail merge?
  • 13 What is an SMTP server name?
  • 14 What is CDO message?
  • 15 How do I do labels from Excel?
  • 16 How do I import data from Excel to Word?
  • 17 How do I do mail merge?
  • 18 How do I save an Excel file as a data source?
  • 19 How do I print labels from Excel without Word?

Can Excel send emails automatically?

Press the Alt + Q keys together to close the Microsoft Visual Basic for Applications window. From now on, when the value you entering in cell D7 is greater than 200, an email with specified recipients and body will be created automatically in Outlook. You can click the Send button to send this email.

How do I send a mass email from an Excel spreadsheet?

Send Personalized Mass Emails From Outlook with Excel

  1. Step 1: Format Your Excel Workbook.
  2. Step 2: Prepare the Document Template for Your Word Mail Merge.
  3. Step 3: Select Your Recipient List.
  4. Step 4: Add Personalized Content to Your Letter.
  5. Step 5: Preview and Finish the Mail Merge Function.
  6. Step 6: Save the Letter.

How can I send email from Excel without Outlook?

How to send email without Outlook in Excel?

  1. Firstly, you need to create a mailing list contains all fields you will include in your email.
  2. In the Create Mailing List dialog box, please do as follows.
  3. Then a mailing list sample table is created.
  4. Select the whole mailing list and then click Kutools Plus > Send Emails.

How do I create a mail merge from Excel?

You can insert one or more mail merge fields that pull the information from your spreadsheet into your document.

  1. Go to Mailings > Insert Merge Field.
  2. Add the field you want.
  3. Repeat steps 1 and 2 as needed.
  4. Choose File > Save.

How do I send an email from Excel to Gmail?

Sending a Workbook via GMail
You need to add code to select the workbook, and then you need to attach the selected file to the email. We will use the Microsoft Office FileDialog command to select the file to send, and then use the AddAttachment property of the email to add the file as an attachement.

Can you mail merge without Outlook?

Mailmerge without using Microsoft Outlook uses only Excel, VBA, Word, and CDOSys. Summary: Send personalized emails to a list of email addresses and names in Microsoft Excel.

How do you do a mail merge in Excel without word?

Re: Using mail merge in excel without word

  1. Create a mapping between the source data and the destination (template) cells.
  2. Select the rows in the source to merge.
  3. In each iteration, copy every source cell to the mapped destination cell, then save the template as it’s own XLS file and publish it to PDF.

Can an Excel spreadsheet be used as the data source for a Word mail merge yes or no?

An essential step in a Word mail merge process is setting up and preparing a data source. You can use an existing Excel data source or build a new one by importing a tab-delimited (.txt) or comma-separated value (.csv) file.

Can you make Avery labels from an Excel spreadsheet?

You can import addresses or other data from an Excel spreadsheet and add them on Avery labels, cards, and tags. Then you can print using Avery Labels, Microsoft, and a standard printer.

How do I mail merge from Excel to Outlook?

How to Email Merge From Excel

  1. Open an Excel workbook containing the names and other identifying data that you want to use in your email.
  2. Open Microsoft Word and type your form letter.
  3. Click on the “Mailings” tab, choose “Start Mail Merge” and click “Email.”
  4. Click “Select Recipients” on the displayed tab.

How do I mail merge from Excel to Word labels?

With your address list set up in an Excel spreadsheet, Outlook Contacts, or a new list you created, you can use mail merge in Word to create mailing labels. Go to Mailings > Start Mail Merge > Labels. In the Label Options dialog box, choose your label supplier in the Label vendors list.

What are the six steps of mail merge?

Note there are 6 steps.

  1. Step 1 – Select Document Type. 1) Click Letters for the document type.
  2. Step 2 – Select Starting Document.
  3. Step 3 – Select Recipients.
  4. Step 4 – Write Your Letter.
  5. Step 5 – Preview Your Letters.
  6. Step 6 – Complete the Merge.
  7. Step 1 – Select Document Type.
  8. Step 2 – Select Starting Document.

What is an SMTP server name?

An SMTP server is the machine that takes care of the whole email delivery process: that’s why to send your messages with an email client or software you need first of all to configure the correct SMTP settings – in particular, the right SMTP address you’re using. (For instance, Gmail’s is smtp.gmail.com).

What is CDO message?

Collaboration Data Objects (CDO), previously known as OLE Messaging or Active Messaging, is an application programming interface included with Microsoft Windows and Microsoft Exchange Server products.

How do I do labels from Excel?

Go to the Mailings tab. Choose Start Mail Merge > Labels. Choose the brand in the Label Vendors box and then choose the product number, which is listed on the label package. You can also select New Label if you want to enter custom label dimensions.

How do I import data from Excel to Word?

Inserting linked Excel data into a Word table

  1. Open the Excel source workbook.
  2. Select the data you want to place in the Word file.
  3. Press Ctrl + C or right-click and choose Copy from the drop-down menu.
  4. Open the Word destination document.
  5. Position the insertion point where you want the linked Excel data to appear.

How do I do mail merge?

How to Use Mail Merge in Microsoft Word

  1. In a blank Microsoft Word document, click on the Mailings tab, and in the Start Mail Merge group, click Start Mail Merge .
  2. Click Step-by-Step Mail Merge Wizard .
  3. Select your document type.
  4. Select the starting document.
  5. Select recipients.
  6. Write the letter and add custom fields.

How do I save an Excel file as a data source?

Using a Microsoft Excel File Stored in a File Directory Data Source

  1. Click the New Data Set toolbar button and select Microsoft Excel File.
  2. Enter a name for this data set.
  3. Click Shared to enable the Data Source list.
  4. Select the data source where the Microsoft Excel File resides.

How do I print labels from Excel without Word?

How to: How to Print labels from Excel without Word

  1. Step 1: Download Excel spread sheet and enable Macros.
  2. Step 2: Paste your single column data into 1A.
  3. Step 3: Press CTRL + e to activate the macro.
  4. Step 4: Choose “3” for number of columns.
  5. Step 5: Set margins to “custom margin”

Although I often refer people to use CDO mail, I have only briefly discussed it in prior postings and I never really gave any usage examples. Today that changes!

So what exactly is CDO Mail and when is it useful?

Collaborative Data Objects – (CDO) is the COM-based interface for accessing Exchange or any other Messaging API (MAPI)-compliant service such as fax services, POP3 services, and so on.Sean McCormick

CDO mail is one of many techniques available to developer to send e-mails.

If you are an MS Access developer you are surely aware of the SendObject method, but it will only allow one attachment and that attachment has to be an Access object (not an external file).

Another very common approach is to use Outlook automation, but with new security impositions by Microsoft it has become unreliable and now requires workarounds. Furthermore, after a recent discussion with fellow MVPs, we find out that having an outdated virus definition can stop longstanding code from working! As such, although powerful, outlook automation simply is not reliable for true production. For production tools, one must then look at integrating tools such as Outlook Redemption, but the down side to this solution is that it requires registering a COM library for it to work.

Which brings us to CDO Mail!

CDO Mail is a technique that binds you directly to your e-mail server to send out email(s).

CDO Mail Pros

  • No e-mail client (Outlook, Thunderbird, …) need be installed
    • Hence you bypass any e-mail client limitations and/or security restrictions
  • Permits multiple attachments to be included
  • Permits external documents as attachments
  • Accepts both plain text and HTML formatted content
  • Can be used in any programs which uses VBA (MS Access, Excel, Word, PowerPoint, MS Project, …)
  • Can even be used in VBScript

CDO Mail Cons

  • Requires knowledge of all the server settings (port, username, password, authentication, …)
  • Does not keep a copy of sent e-mails so CCing or BCCing yourself becomes useful for archive purposes
  • Does not permit attaching database objects directly, but you can export them or print them as PDFs and attach those

CDO Mail VBA Code Sample

Below is a sample CDO Mail function I created many moons ago for my own purposes and have tweak slightly over the years.

Const cdoSendUsingPickup = 1 'Send message using the local SMTP service pickup directory.
Const cdoSendUsingPort = 2 'Send the message using the network (SMTP over the network).

Const cdoAnonymous = 0 'Do not authenticate
Const cdoBasic = 1 'basic (clear-text) authentication
Const cdoNTLM = 2 'NTLM

Function SendCDOMail(sTo As String, sSubject As String, sBody As String, _
                     Optional sBCC As Variant, Optional AttachmentPath As Variant)
    On Error GoTo Error_Handler
    Dim objCDOMsg       As Object
    Dim i               As Long
 
'    Set objCDOMsg = New CDO.Message             'Early Binding -> Microsoft CDO for Windows 2000 Library
    Set objCDOMsg = CreateObject("CDO.Message") 'Late Binding
 
    'CDO Configuration
    With objCDOMsg.Configuration.Fields
        '
        .Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = cdoSendUsingPort
        'Server port (typically 25, 465, 587) '***The next line is commented out because of the use of SSL encryption***
        '.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 465 'Commonly -> 465 SSL, 587 TLS
        'SMTP server IP or Name
        .Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "mail.hitterslongrun.com"
        'Type of authentication, NONE, Basic (Base64 encoded), NTLM
        .Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = cdoBasic
        'SMTP Account User ID
        .Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "accounts@hitterslongrun.com"
        'SMTP Account Password
        .Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "Uhdje!@@0#"
        'Number of seconds to wait for a response from the server before aborting
        .Item("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 10
        'Use SSL for the connection (False or True) -> If using SSL, do not specify the Port above
        .Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True '!!!!Always use some form of encryption!!!!
        'Use TLS for the connection (False or True) - See the note below
        '.Item("http://schemas.microsoft.com/cdo/configuration/sendtls") = True 'Does not work in CDO
        .Update
    End With
 
    'CDO Message
    objCDOMsg.Subject = sSubject
    objCDOMsg.From = "accounts@hitterslongrun.com"
    objCDOMsg.To = sTo
    'objCDOMsg.TextBody = sBody 'This would be for plain text e-mails
    objCDOMsg.HTMLBody = sBody 'This would be for HTML formatted e-mails using HTML tags
    ' Add attachments to the message.
    If Not IsMissing(AttachmentPath) Then
        If IsArray(AttachmentPath) Then
            For i = LBound(AttachmentPath) To UBound(AttachmentPath)
                If AttachmentPath(i) <> "" And AttachmentPath(i) <> "False" Then
                    objCDOMsg.AddAttachment AttachmentPath(i)
                End If
            Next i
        Else
            If AttachmentPath <> "" Then
                objCDOMsg.AddAttachment AttachmentPath
            End If
        End If
    End If

    '****Do not forget although we can configure the following, the recipient can disable the functionality
    '       at their end on the server/email client, so this truly is not reliable!
    'Read receipt
'    objCDOMsg.Fields(CdoMailHeader.cdoReturnReceiptTo) = "accounts@hitterslongrun.com"                    'Early Binding
    objCDOMsg.Fields("urn:schemas:mailheader:return-receipt-to") = "accounts@hitterslongrun.com"           'Late Binding
    'Delivery receipt
'    objCDOMsg.Fields(CdoMailHeader.cdoDispositionNotificationTo) = "accounts@hitterslongrun.com"          'Early Binding
    objCDOMsg.Fields("urn:schemas:mailheader:disposition-notification-to") = "accounts@hitterslongrun.com" 'Late Binding

    objCDOMsg.Send
 
Error_Handler_Exit:
    On Error Resume Next
    Set objCDOMsg = Nothing
    Exit Function
 
Error_Handler:
    MsgBox "The following error has occurred." & vbCrLf & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Source: SendCDOMail" & vbCrLf & _
           "Error Description: " & Err.Description, _
           vbCritical, "An Error has Occurred!"
    Resume Error_Handler_Exit
End Function

Now that we have a function to call, we can now send out an e-mail by making a single call to the function along the lines of:

Call SendCDOMail("RecipientEmail", "Subject", "EmailBody", , array("C:UsersTestDocumentssample.pdf", "C:UsersTestDocumentsballons.gif"))

Recommendation!

I HIGHLY recommend you always use SSL. Security measures should always be implemented.

CDO And TLS

There is great debate regarding CDO and TLS. Even though the option seems to exist, people state it does nothing and doesn’t truly work. This is way out of my field of expertise, so I will not comment at this point in time. Furthermore, I have been unable to find any official documentation on the subject as Microsoft regularly purges KB article, and other pages leaving us with nothing but dead links. (Thank you Microsoft!)

As such, I’ve left the line of code in my sample, but it is a use it at your on risk, and hopefully you know what your doing to validate it actually works.

A Few Resources on the Subject

Sending mail from Excel with CDO

The example code is using CDOSYS (CDO for Windows 2000). It does not depend on MAPI or CDO and hence is dialog free and does not use your mail program to send email.

VBScript To Send Email Using CDO

VBScript code sample for using CDO Mail

E-mail

MS Access — How To Send An Email

Now here’s a question we see all the time in the various forums. As usual, there are a number of ways to accomplish this and which one you should use has a lot to do with your needs and abilities. In this post, I’m going to briefly discuss the 3 most popular approaches: SendObject method…

Continue reading

CDO: Part I

MSDN Library: Periodics 2000: Excerpt:

письмо excel

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

Данная статья описывает три способа отправки писем с помощью VBA в Excel. Вы можете скачать файл с примером отправки email с помощью VBA в Excel.

Отправить письмо в Excel с помощью VBA

Один из самых простых способов для автоматизации отправки почты с Excel заключается в вызове функции Create («ObjectOutlook.Application»). Данная функция возвращающает ссылку на ActiveX объект (в данном случает приложение Outlook), которое затем используется для создания и отправки электронной почты.

Чтобы проверить данный способ в работе, скопируйте и вставьте код ниже в VB редактор.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

Sub Send_Email_Using_VBA()
Dim Email_Subject, Email_Send_From, Email_Send_To, _
Email_Cc, Email_Bcc, Email_Body As String
Dim Mail_Object, Mail_Single As Variant
Email_Subject = «Попытка отправить письмо с помощью VBA»
Email_Send_From = «exceltipmail@gmail.com»
Email_Send_To = » exceltipmail@gmail.com «
Email_Cc = » exceltipmail@gmail.com «
Email_Bcc = » exceltipmail@gmail.com «
Email_Body = «Поздравляем!!!! Ваше письмо успешно отправлено !!!!»
On Error GoTo debugs
Set Mail_Object = CreateObject(«Outlook.Application»)
Set Mail_Single = Mail_Object.CreateItem(0)
With Mail_Single
.Subject = Email_Subject
.To = Email_Send_To
.cc = Email_Cc
.BCC = Email_Bcc
.Body = Email_Body
.send
End With
debugs:
If Err.Description &lt;&gt; «» Then MsgBox Err.Description
End Sub

В качестве напоминания: Когда вы пытаетесь отправить письмо вышеуказанным способом, система безопасности будет выдавать каждый раз предупреждающее окно, в котором будет говориться о том, что Программа пытается отправить сообщение от вашего имени… и возможности обойти этот шаг нет.

предупреждение об отправке письма

К счастью, существует еще два способа, с помощью которых данный вопрос может быть решен: первый – через использование CDO, второй – имитирующий использование событий нажатий клавиш клавиатуры.

Отправить письмо в Excel с помощью CDO

Что такое CDO? CDO является библиотекой объектов, которая предоставляет интерфейс Messaging Application Programming Interface (MAPI). CDO позволяет манипулировать обменом данных, и отправлять и получать сообщения.

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

В нашем примере мы используем функцию CreateObject («CDO.Message»). Важно отметить, что необходимо правильно установить конфигурацию SMTP сервера, чтобы не допустить появления ошибок Run-time error 2147220973(80040213) или sendUsing configuration value is invalid. Пример ниже настроен на отправку сообщений через почту Google (Gmail). Для других почтовых серверов, вам потребуется ввести свои значения SMTP-сервера и SMTP-порта.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

Sub CDO_Mail_Small_Text_2()
Dim iMsg As Object
Dim iConf As Object
Dim strbody As String
Dim Flds As Variant
Set iMsg = CreateObject(«CDO.Message»)
Set iConf = CreateObject(«CDO.Configuration»)
iConf.Load -1
Set Flds = iConf.Fields
With Flds
.Item(«https://schemas.microsoft.com/cdo/configuration/smtpusessl») = True
.Item(«https://schemas.microsoft.com/cdo/configuration/smtpauthenticate») = 1
.Item(«https://schemas.microsoft.com/cdo/configuration/sendusername») = «Полный адрес вашего GMail ящика»
.Item(«https://schemas.microsoft.com/cdo/configuration/sendpassword») = «GMail пароль»
.Item(«https://schemas.microsoft.com/cdo/configuration/smtpserver») = «smtp.gmail.com»
.Item(«https://schemas.microsoft.com/cdo/configuration/sendusing») = 2
.Item(«https://schemas.microsoft.com/cdo/configuration/smtpserverport») = 465
.Update
End With
strbody = «Поздравляем!!!! Ваше письмо успешно отправлено !!!!»
With iMsg
Set .Configuration = iConf
.To = «Почтовый адрес получателя»
.CC = «»
.BCC = «»
.From = «»«ВашеИмя»» &lt;Reply@something.nl&gt;»
.Subject = «Попытка отправить письмо с помощью CDO»
.TextBody = strbody
.Send
End With
End Sub

Обратите внимание, чтобы воспользоваться данным методом вам необходимо подключить библиотеку CDO в редакторе макросов Tool –> References.

Отправить письмо с помощью CDO

Отправить письмо в Excel с помощью Send Keys

Другой способ отправки email с помощью Excel – использование команды ShellExecute, которая выполняет любую программу в VBA. Команда ShellExecute используется для загрузки документа с соответствующей программой. По сути, вы создаете объект String (текстовые данные) и передаете его в качестве параметра для функции ShellExecute. Остальная часть операций выполняется в окнах. Автоматически определяется, какая программа связана с данным типом документа и используется для загрузки документа. Вы можете использовать функцию ShellExecute, чтобы открыть Internet Explorer, Word, Paint и множество других приложений. В коде ниже используется задержка в три секунды, чтобы убедиться, что отправляемое письмо корректно и для возможности предотвратить отправку, если вы вдруг нашли какие-нибудь недочеты.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

Sub Send_Email_Using_Keys()
Dim Mail_Object As String
Dim Email_Subject, Email_Send_To, Email_Cc, Email_Bcc, Email_Body As String
Email_Subject = «Попытка отправить письмо с помощью SendKeys»
Email_Send_To = «exceltipmail@gmail.com «
Email_Cc = «exceltipmail@gmail.com «
Email_Bcc = «exceltipmail@gmail.com «
Email_Body = «Поздравляем!!!! Ваше письмо успешно отправлено !!!!»
Mail_Object = «mailto:» & Email_Send_To & «?subject=» & Email_Subject & «&body=» & Email_Body & «&cc=» & Email_Cc & «&bcc=» & Email_Bcc
On Error GoTo debugs
ShellExecute 0&, vbNullString, Mail_Object, vbNullString, vbNullString, vbNormalFocus
Application.Wait (Now + TimeValue(«0:00:03»))
Application.SendKeys «^({ENTER})»
Application.SendKeys («{ENTER}»)
debugs:
If Err.Description <> «» Then MsgBox Err.Description
End Sub

Cкачать файл с примером отправки email с помощью VBA в Excel

Last Updated on Wed, 01 Mar 2023 |
Excel Tips

This article shows three methods using which you can send email using VBA in Excel. You can download a working example of sending email using vba in Excel here.

Excel allows you to create the best-in-class charts, work with large amount of data and data sources work with images, flowcharts and what not. And if that was not enough, you can use the inbuilt vba editor to automate sending emails from excel on your behalf.

(Download example at the end of this post)

Here’s how:

Send Email Using VBA

One of the easiest means to automate sending emails from Excel is to invoke the Create(“ObjectOutlook.Application”) function. This returns the reference to an (activeX) object, in this case the Outlook Application, which is then used further for creating and dispatching an email.

You can copy paste the code below to make this happen:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

Sub Send_Email_Using_VBA()
Dim Email_Subject, Email_Send_From, Email_Send_To, _
Email_Cc, Email_Bcc, Email_Body As String
Dim Mail_Object, Mail_Single As Variant
Email_Subject = «Trying to send email using VBA»
Email_Send_From = «[email protected]»
Email_Send_To = «[email protected]»
Email_Cc = «[email protected]»
Email_Bcc = «[email protected]»
Email_Body = «Congratulations!!!! You have successfully sent an e-mail using VBA !!!!»
On Error GoTo debugs
Set Mail_Object = CreateObject(«Outlook.Application»)
Set Mail_Single = Mail_Object.CreateItem(0)
With Mail_Single
.Subject = Email_Subject
.To = Email_Send_To
.cc = Email_Cc
.BCC = Email_Bcc
.Body = Email_Body
.send
End With
debugs:
If Err.Description <> «» Then MsgBox Err.Description
End Sub

As a reminder: When you send email using the vba code mentioned above, a pop-up warning the users that the “A program is trying to automatically send email on your behalf. Do you want to allow this?” appears. Now that’s a valid security warning and there is no direct work around to it. However there are two other means by which this task can be accomplished, one through the use of CDO and the other ones that simulates the use of keyboard key press events.

Send Email Using CDO

What is CDO. According to Technet, CDO is an object library that exposes the interfaces of the Messaging Application Programming Interface (MAPI). CDO allows you to manipulate Exchange data and to send and receive messages.

The use of CDO may be preferable in cases where you’d want to prevent the security pop-up from appearing with “a program is trying to automatically send email on your behalf” warning and therefore delaying the sending of email till the user provide a response.

In our example, we use the CreateObject(“CDO.Message”) function. An important point to note here is to set the SMTP configuration properly so as to prevent the dreaded “Run-time error
-2147220973(80040213)” or the “sendUsing configuration value is invalid” errors from appearing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

Sub Send_Email_Using_CDO()
Dim CDO_Mail_Object As Object
Dim CDO_Config As Object
Dim SMTP_Config As Variant
Dim Email_Subject, Email_Send_From, Email_Send_To, Email_Cc, Email_Bcc, Email_Body As String
Email_Subject = «Trying to send email using CDO»
Email_Send_From = «[email protected]»
Email_Send_To = «[email protected]»
Email_Cc = «[email protected]»
Email_Bcc = «[email protected]»
Email_Body = «Congratulations!!!! You have successfully sent an e-mail using CDO !!!!»
Set CDO_Mail_Object = CreateObject(«CDO.Message»)
On Error GoTo debugs
Set CDO_Config = CreateObject(«CDO.Configuration»)
CDO_Config.Load -1
Set SMTP_Config = CDO_Config.Fields
With SMTP_Config
.Item(«http://schemas.microsoft.com/cdo/configuration/sendusing») = 2
‘please put your server name below
.Item(«http://schemas.microsoft.com/cdo/configuration/smtpserver») = «YOURSERVERNAME»
.Item(«http://schemas.microsoft.com/cdo/configuration/smtpserverport») = 25
.Update
End With
With CDO_Mail_Object
Set .Configuration = CDO_Config
End With
CDO_Mail_Object.Subject = Email_Subject
CDO_Mail_Object.From = Email_Send_From
CDO_Mail_Object.To = Email_Send_To
CDO_Mail_Object.TextBody = Email_Body
CDO_Mail_Object.cc = Email_Cc ‘Use if needed
CDO_Mail_Object.BCC = Email_Bcc ‘Use if needed
‘CDO_Mail_Object.AddAttachment FileToAttach ‘Use if needed
CDO_Mail_Object.send
debugs:
If Err.Description <> «» Then MsgBox Err.Description
End Sub

Send Email Using Send Keys

Another way to send an email is to use the ShellExecute command to execute any program within vba. The ShellExecute command can be used to load a document with the associated program. In essence, you create a string object and pass that as a parameter to the SheelExecute function. The rest of the work is done by windows. It automatically decides which program is associated with the given document type and uses that to load the document. You can use the ShellExecute function to open explorer, word, paint and a host of other applications. The operation may be slow and you don’t want to send keys even before the email appears on screen so we wait a couple of seconds, make sure that the email request is fully processes and then send the keys. Sending keys before time will prevent the email from being dispatched.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

Sub Send_Email_Using_Keys()
Dim Mail_Object As String
Dim Email_Subject, Email_Send_To, Email_Cc, Email_Bcc, Email_Body As String
Email_Subject = «Trying to send email using Keys»
Email_Send_To = «[email protected]»
Email_Cc = «[email protected]»
Email_Bcc = «[email protected]»
Email_Body = «Congratulations!!!! You have successfully sent an e-mail using Keys !!!!»
Mail_Object = «mailto:» & Email_Send_To & «?subject=» & Email_Subject & «&body=» & Email_Body & «&cc=» & Email_Cc & «&bcc=» & Email_Bcc
On Error GoTo debugs
ShellExecute 0&, vbNullString, Mail_Object, vbNullString, vbNullString, vbNormalFocus
Application.Wait (Now + TimeValue(«0:00:03»))
Application.SendKeys «%s»
debugs:
If Err.Description <> «» Then MsgBox Err.Description
End Sub

(Code courtesy: www.ozgrid.com)

Continue reading here: How to Create a Dashboard in Excel

Was this article helpful?

Dear Readers,

In this article, we are going to learn how to send an email automatically by Excel Excel VBA. While executing the Excel Macro, sometimes you may need to send some Details or Results directly to your email ID or any other ID using Excel Macro. If you have some report or details which you want to send in a mail without log-in to your email account.
This you are going to achieve by using CDO Object.

What is CDO (Collaboration Data Objects)??

.
This Object is basically used for Active Messaging, Enables user to Access Global Server Objects and Address List For more about this read this Microsoft Help.

In Microsoft Excel, to use this Object you need to Add CDO Reference.

Add CDO Reference

Add CDO Reference

Note: Without adding this reference you can Run the below Code. For running this Code, you can use below line to create Object runtime:


Set myMail = CreateObject("CDO.Message")

In this article, i will explain you 2 simple methods, to send an email by Excel VBA.

1. Excel VBA: Send email from Gmail



Sub SendEmailUsingGmail()
    
    On Error GoTo Err
    
    Dim NewMail As Object
    Dim mailConfig As Object
    Dim fields As Variant
    Dim msConfigURL As String
    
    Set NewMail = CreateObject("CDO.Message")
    Set mailConfig = CreateObject("CDO.Configuration")
    
    ' load all default configurations
    mailConfig.Load -1
    
    Set fields = mailConfig.fields
    
'Set All Email Properties
    
    With NewMail
        .Subject = "Test Mail from LearnExcelMacro.com"
        .From = "email@gmail.com"
        .To = "email2@gmail.com;email3@gmail.com"
        .CC = "email4@gmail.com"
        .BCC = ""
        .textbody = ""
    End With
    
    msConfigURL = "http://schemas.microsoft.com/cdo/configuration"
    
    With fields
        'Enable SSL Authentication
        .Item(msConfigURL & "/smtpusessl") = True
        
        'Make SMTP authentication Enabled=true (1)
        .Item(msConfigURL & "/smtpauthenticate") = 1
        
        'Set the SMTP server and port Details
        'To get these details you can get on Settings Page of your Gmail Account
        .Item(msConfigURL & "/smtpserver") = "smtp.gmail.com"
        .Item(msConfigURL & "/smtpserverport") = 465
        .Item(msConfigURL & "/sendusing") = 2
        
        'Set your credentials of your Gmail Account
        .Item(msConfigURL & "/sendusername") = "email@gmail.com"
        .Item(msConfigURL & "/sendpassword") = "********"
        
        'Update the configuration fields
        .Update
        
    End With
    NewMail.Configuration = mailConfig
    NewMail.Send
    MsgBox ("Mail has been Sent")
    
Exit_Err:
    
    Set NewMail = Nothing
    Set mailConfig = Nothing
    End
    
Err:
    Select Case Err.Number
    
    Case -2147220973  'Could be because of Internet Connection
        MsgBox " Could be no Internet Connection !!  -- " & Err.Description
        
    Case -2147220975  'Incorrect credentials User ID or password
        MsgBox "Incorrect Credentials !!  -- " & Err.Description
        
    Case Else   'Rest other errors
        MsgBox "Error occured while sending the email !!  -- " & Err.Description
    End Select
    
    Resume Exit_Err
    
End Sub

2. Excel VBA: Send email from Yahoo



Sub SendEmailUsingYahoo()
    
    On Error GoTo Err
    
    Dim NewMail As Object
    Dim mailConfig As Object
    Dim fields As Variant
    Dim msConfigURL As String
    
    Set NewMail = CreateObject("CDO.Message")
    Set mailConfig = CreateObject("CDO.Configuration")
    
    ' load all default configurations
    mailConfig.Load -1
    
    Set fields = mailConfig.fields
    
'Set All Email Properties
    
    With NewMail
        .Subject = "Test Mail from LearnExcelMacro.com"
        .From = "email@yahoo.co.in"
        .To = "email1@gmail.com;email2@yahoo.com"
        .CC = "email@email.com"
        .BCC = ""
        .textbody = ""
    End With
    
    msConfigURL = "http://schemas.microsoft.com/cdo/configuration"
    
    With fields
        'Enable SSL Authentication
        .Item(msConfigURL & "/smtpusessl") = True
        
        'Make SMTP authentication Enabled=true (1)
        .Item(msConfigURL & "/smtpauthenticate") = 1
        
        'Set the SMTP server and port Details
        'To get these details you can get on Settings Page of your yahoo Account
        .Item(msConfigURL & "/smtpserver") = "smtp.mail.yahoo.com"
        .Item(msConfigURL & "/smtpserverport") = 465
        .Item(msConfigURL & "/sendusing") = 2
        
        'Set your credentials of your yahoo Account
        .Item(msConfigURL & "/sendusername") = "email@yahoo.co.in"
        .Item(msConfigURL & "/sendpassword") = "******"
        
        'Update the configuration fields
        .Update
        
    End With
    NewMail.Configuration = mailConfig
    NewMail.Send
    MsgBox ("Mail has been Sent")
    
Exit_Err:
    
    Set NewMail = Nothing
    Set mailConfig = Nothing
    End
    
Err:
    Select Case Err.Number
    
    Case -2147220973  'Could be because of Internet Connection
        MsgBox " Could be no Internet Connection !!  -- " & Err.Description
        
    Case -2147220975  'Incorrect credentials User ID or password
        MsgBox "Incorrect Credentials !!  -- " & Err.Description
        
    Case Else   'Rest other errors
        MsgBox "Error occured while sending the email !!  -- " & Err.Description
    End Select
    
    Resume Exit_Err
    
End Sub
 

Excel VBA to Send Email with HTML Body

For sending HTML Body you just need to Change the Email Properties which you are setting above



With NewMail
  .Subject = "Test Mail from LearnExcelMacro.com"
  .From = "email@yahoo.com"
  .To = "email2@gmail.com;email3@yahoo.com"
  .CC = "email@email.com"
  .BCC = ""
  .HTMLBody = "Write your complete HTML Page"
End With

Excel VBA to Send Email with an Attachment


With NewMail
  .Subject = "Test Mail from LearnExcelMacro.com"
  .From = "vishwamitra01@yahoo.com"
  .To = "vishwamitra02@gmail.com;info@learnexcelmacro.com"
  .CC = "vishwamitra01@gmail.com"
  .BCC = ""
  .HTMLBody = "Write your complete HTML Page"

' For multiple Attachment you can add below lines as many times

  .AddAttachment "C:ExcelMacro-help.xls"
  .AddAttachment "C:ExcelMacro-help2.xls"
End With

Понравилась статья? Поделить с друзьями:
  • What is captions in word
  • What is building blocks in word
  • What is brexit word
  • What is box plot in excel
  • What is box out word