VBA技術解説
VBAでメール送信する(CDO:Microsoft Collaboration Data Objects)

ExcelマクロVBAの問題点と解決策、VBAの技術的解説
公開日:2013-06-26 最終更新日:2020-04-10

VBAでメール送信する(CDO:Microsoft Collaboration Data Objects)


VBAでメール送信する方法はいろいろありますが、
ここでは、CDO(Microsoft Collaboration Data Objects)を使っての送信方法を解説します。


メール送信は、メーラーを使う方法や、フリーのDLLを使う方法等もありますが、
まずは、Windowsに標準であるCDOを使ってみましょう。

ただし、このCDOも環境によってはインストールされていない場合もあるようですが、
ほとんどのWindows環境で問題なく使えるはずです。

私も頻繁に使う訳ではありませんので、自身の覚書も兼ねて掲載します。

バインディング方法

事前バインディング

Microsoft CDO for Windows 2000 Library
これを参照設定し、
Dim 変数 As New CDO.Message

遅延バインディング(実行時バインディング)

Dim 変数 As Object
Set 変数 = CreateObject("CDO.Message")

CDOは情報も少なく、設定値の定数も調べるときに苦労してしまいますので、
事前バインディングすることで、自動メンバー表示を参考にVBAを作成してください。
以下は、事前バインディングでのサンプルコードです。

CDOを使ったメール送信のサンプルVBA

Sub sample()
  Dim objCDO As New CDO.Message
  With objCDO
    With .Configuration.Fields '設定項目
      .Item(cdoSMTPServer) = "SMTPサーバ" 'SMTPサーバ名
      .Item(cdoSendUsingMethod) = cdoSendUsingPort '外部SMTP指定
      .Item(cdoSMTPServerPort) = 465 'ポート№
      .Item(cdoSMTPConnectionTimeout) = 60 'タイムアウト
      .Item(cdoSMTPAuthenticate) = cdoBasic 'SMTP認証
      .Item(cdoSMTPUseSSL) = True 'SSL
      .Item(cdoSendUserName) = "ユーザー名" '送信ユーザー
      .Item(cdoSendPassword) = "パスワード" '送信パスワード
      .Item(cdoLanguageCode) = CdoCharset.cdoShift_JIS '文字セット指定
      .Update '設定を更新
    End With
    With .Fields
      '重要度、通常は以下のどちらかで良いでしょう
      .Item("urn:schemas:mailheader:X-Priority") = 1
      .Item("urn:schemas:mailheader:X-MsMail-Priority") = "High"
      .Update '設定を更新
    End With
    .MDNRequested = True '開封確認
    .MimeFormatted = True 'MIMEを使って書式設定
    .From = "送信元メールアドレス"
    .To = "宛先メールアドレス"
    .Subject = "テスト"
    .TextBody = "本文"
    .Send '送信
  End With
  Set objCDO = Nothing
End Sub

上記の太字部分は変更すべき箇所です、メールアドレスは当然ですね。
使用している定数については最後に解説しています。
なかなか資料もそろいませんが、各プロパティ・メソッドについてまとめておきます。

CDOのプロパティ

名前 説明
Attachments The Attachments property specifies the collection of attachments for this message.
This property is read-only.
Attachmentsの資産は、このメッセージのために付属品のコレクションを指定します。
この資産はリードオンリーです。
AutoGenerateTextBody Indicates whether the TextBody of a message should automatically be generated from the contents of the HTMLBody property for a multipart/alternative message.
メッセージのTextBodyがマルチパート/代わりのメッセージのためにHTMLBodyの資産の内容から自動的に発生しなければならないかどうか示します。
BCC The blind carbon copy (Bcc) recipients for this message.
このメッセージのためのブラインド・カーボンコピー(Bcc)受取人。
BodyPart The IBodyPart interface on this object. This property is read-only.
IBodyPartは、この物の上で結びつきます。この資産はリードオンリーです。
CC The informational carbon copy (Cc) recipients for this message.
このメッセージのための情報のカーボンコピー(Cc)受取人。
Configuration The Configuration object for the message.
メッセージのConfiguration対象。
DataSource The IDataSource interface on this object.
This property is read-only.
IDataSourceは、この物の上で結びつきます。
この資産はリードオンリーです。
DSNOptions The Delivery Status Notification (DSN) options for the message.
メッセージのためのDelivery Status Notification(DSN)オプション。
EnvelopeFields The SMTP and Network News Transfer Protocol (NNTP) envelope fields of the message.
This property is read-only.
SMTPとメッセージのNetwork News Transfer Protocol(NNTP)封筒分野。
この資産はリードオンリーです。
Fields The Fields collection for the object. This property is read-only.
物のためのフィールズ収集。この資産はリードオンリーです。
FollowUpTo The newsgroups to which any responses to this message should be posted.
このメッセージへのどんな反応でも掲示されなければならないニュースグループ。
From The e-mail addresses of the principal author or authors of this message.
このメッセージの主要な著者または著者の電子メール・アドレス。
HTMLBody The HTML representation of the message.
メッセージのHTML代表。
HTMLBodyPart The BodyPart object containing the HTML representation of the message.
This property is read-only.
BodyPartは、メッセージのHTML代表を含んで反対します。
この資産はリードオンリーです。
Keywords A list of keywords for this message.
このメッセージのキーワードのリスト。
MDNRequested Indicates whether a Mail Delivery Notification (MDN) report is requested for a message.
Mail Delivery Notification(MDN)報告がメッセージのために要請されるかどうか示します。
MimeFormatted Indicates whether or not this message is to be formatted using the Multipurpose Internet Mail Extensions (MIME) formatting scheme.
このメッセージが計画をフォーマット化している多目的インターネットメール拡張仕様(MIME)を使って書式を設定されることになっているかどうか示します。
Newsgroups The newsgroup recipients for the message.
メッセージのためのニュースグループ受取人。
Organization Contains a description of the organization to which the sender belongs.
送り主が属する組織の説明を含みます。
ReceivedTime The date/time this message was delivered to the server.
This property is read-only.
このメッセージがそうであった日付/時間は、サーバーに配達しました。
この資産はリードオンリーです。
ReplyTo The address to which replies should be sent.
返事が送られなければならないアドレス。
Sender The address of the user or agent that actually submits the message.
メッセージを実際に提出するユーザーまたはエージェントのアドレス。
SentOn The date/time this message was submitted to the server.
This property is read-only.
このメッセージがそうであった日付/時間は、サーバーを受け入れました。
この資産はリードオンリーです。
Subject The subject of the message.
メッセージの対象。
TextBody The plain text representation of the body of this message.
このメッセージの本文のプレーンテキスト代表。
TextBodyPart Returns a body part object containing the text content of this message.
This property is read-only.
このメッセージのテキスト内容を含んでいる部位物を返します。
この資産はリードオンリーです。
To Contains a list of principal (To) recipients for this message.
このメッセージのために校長(ために)受取人のリストを含みます。
※下段の日本語は、自動翻訳したものです。

CDOのメソッド

名前 説明
AddAttachment Adds an attachment to this message.
付属品をこのメッセージに加えます。
AddRelatedBodyPart The AddRelatedBodyPart method adds a BodyPart object that is referenced by content in the HTML body of the message.
AddRelatedBodyPart方法は、メッセージのHTML本文で内容によってリファレンスをつけられるBodyPart物を加えます。
CreateMHTMLBody The CreateMHTMLBody method converts the contents of an entire Web page into a MIME Encapsulation of Aggregate HTML Documents (MHTML) formatted message body.
CreateMHTMLBody方法は、全てのウェブページの内容をAggregate HTML Documents(MHTML)書式を設定されたメッセージ体のMIME Encapsulationに変えます。
Forward The Forward method creates and returns another message that can be used to forward this message.
Forward方法は、このメッセージを進めるのに用いられることができるもう一つのメッセージを作成して、返します。
GetInterface Returns the specified dual interface on the object.
物の上に指定された二重インターフェースを返します。
GetStream The GetStream method returns this message in serialized (wire-transport) format in a Microsoft? ActiveX? Data Objects (ADO) Stream object.
GetStream方法は、Microsoft?ActiveX?Data Objects(ADO)Stream物で、順番に並べられた(ワイヤー-輸送)フォーマットで、このメッセージを返します。
Post The Post method posts this message to the specified newsgroups.
ポースト方法は、指定されたニュースグループにこのメッセージを送ります。
PostReply The PostReply method creates and returns another message that can be used to post a reply to this message.
PostReplyな方法は、このメッセージに対する返事を記録するのに用いられることができるもう一つのメッセージを作成して、返します。
Reply The Reply method creates and returns another message that can be used to reply to the sender of this message.
Replyな方法は、このメッセージの送り主に答えるのに用いられることができるもう一つのメッセージを作成して、返します。
ReplyAll The ReplyAll method creates and returns another message that can be used to reply to the sender and all recipients.
ReplyAll方法は、送り主とすべての受取人に答えるのに用いられることができるもう一つのメッセージを作成して、返します。
Send The Send method sends the message.
Send方法は、メッセージを送ります。
※下段の日本語は、自動翻訳したものです。

CDO.Configuration.Fields.Item

以下は初期状態の値です。

Item Value
0 languagecode
1 postusing
2 sendemailaddress
3 sendpassword
4 sendusername
5 senduserreplyemailaddress
6 sendusing
7 smtpaccountname
8 smtpauthenticate
9 smtpconnectiontimeout
10 smtpserver
11 smtpserverport
12 usemessageresponsetext
13 urn:schemas:calendar:timezoneid
CdoConfigurationのConstant
以下のValueは、先頭に
http://schemas.microsoft.com/cdo/configuration/
が付きます、つまり、
http://schemas.microsoft.com/cdo/configuration/autopromotebodyparts
のようになります。

Constant Value
cdoAutoPromoteBodyParts autopromotebodyparts
cdoFlushBuffersOnWrite flushbuffersonwrite
cdoHTTPCookies httpcookies
cdoLanguageCode languagecode
cdoNNTPAccountName nntpaccountname
cdoNNTPAuthenticate nntpauthenticate
cdoNNTPConnectionTimeout nntpconnectiontimeout
cdoNNTPServer nntpserver
cdoNNTPServerPickupDirectory nntpserverpickupdirectory
cdoNNTPServerPort nntpserverport
cdoNNTPUseSSL nntpusessl
cdoPostEmailAddress postemailaddress
cdoPostPassword postpassword
cdoPostUserName postusername
cdoPostUserReplyEmailAddress postuserreplyemailaddress
cdoPostUsingMethod postusing
cdoSaveSentItems savesentitems
cdoSendEmailAddress sendemailaddress
cdoSendPassword sendpassword
cdoSendUserName sendusername
cdoSendUserReplyEmailAddress senduserreplyemailaddress
cdoSendUsingMethod sendusing
cdoSMTPAccountName smtpaccountname
cdoSMTPAuthenticate smtpauthenticate
cdoSMTPConnectionTimeout smtpconnectiontimeout
cdoSMTPServer smtpserver
cdoSMTPServerPickupDirectory smtpserverpickupdirectory
cdoSMTPServerPort smtpserverport
cdoSMTPUseSSL smtpusessl
cdoURLGetLatestVersion urlgetlatestversion
cdoURLProxyBypass urlproxybypass
cdoURLProxyServer urlproxyserver
cdoUseMessageResponseText usemessageresponsetext

CDO.Fields.Item

以下は初期状態の値です。

Item Value
0 DAV:contentclass
1 http://schemas.microsoft.com/exchange/sensitivity
2 urn:schemas:httpmail:content-media-type
3 urn:schemas:httpmail:hasattachment
4 urn:schemas:httpmail:htmldescription
5 urn:schemas:httpmail:importance
6 urn:schemas:httpmail:priority
7 urn:schemas:httpmail:textdescription
8 urn:schemas:mailheader:content-class
9 urn:schemas:mailheader:content-transfer-encoding
10 urn:schemas:mailheader:content-type
11 urn:schemas:mailheader:importance
12 urn:schemas:mailheader:priority
13 urn:schemas:mailheader:thread-index

上記サンプルのように、
.Item("urn:schemas:mailheader:X-Priority") = 1
.Item("urn:schemas:mailheader:X-MsMail-Priority") = "High"
これらで、初期で存在しない場合は追加されます。
ここでの項目は、メーラーに依存するようですので、複数の環境でテストする必要があります。

ConstantやEnumについて

上記VBAサンプルでは、
cdoSMTPServer
cdoSendUsingPort
CdoCharset
等々、これらの定数が使われています。
属するメンバーは事前バインディングしていれば候補表示されます。
トップのメンバーはCDOになります。

VBA マクロ CDO メール

上記VBAサンプルで使用しているものは、

CdoConfiguration

VBA マクロ CDO メール

Constant Value
cdoAutoPromoteBodyParts http://schemas.microsoft.com/cdo/configuration/autopromotebodyparts
cdoFlushBuffersOnWrite http://schemas.microsoft.com/cdo/configuration/flushbuffersonwrite
cdoHTTPCookies http://schemas.microsoft.com/cdo/configuration/httpcookies
cdoLanguageCode http://schemas.microsoft.com/cdo/configuration/languagecode
cdoNNTPAccountName http://schemas.microsoft.com/cdo/configuration/nntpaccountname
cdoNNTPAuthenticate http://schemas.microsoft.com/cdo/configuration/nntpauthenticate
cdoNNTPConnectionTimeout http://schemas.microsoft.com/cdo/configuration/nntpconnectiontimeout
cdoNNTPServer http://schemas.microsoft.com/cdo/configuration/nntpserver
cdoNNTPServerPickupDirectory http://schemas.microsoft.com/cdo/configuration/nntpserverpickupdirectory
cdoNNTPServerPort http://schemas.microsoft.com/cdo/configuration/nntpserverport
cdoNNTPUseSSL http://schemas.microsoft.com/cdo/configuration/nntpusessl
cdoPostEmailAddress http://schemas.microsoft.com/cdo/configuration/postemailaddress
cdoPostPassword http://schemas.microsoft.com/cdo/configuration/postpassword
cdoPostUserName http://schemas.microsoft.com/cdo/configuration/postusername
cdoPostUserReplyEmailAddress http://schemas.microsoft.com/cdo/configuration/postuserreplyemailaddress
cdoPostUsingMethod http://schemas.microsoft.com/cdo/configuration/postusing
cdoSaveSentItems http://schemas.microsoft.com/cdo/configuration/savesentitems
cdoSendEmailAddress http://schemas.microsoft.com/cdo/configuration/sendemailaddress
cdoSendPassword http://schemas.microsoft.com/cdo/configuration/sendpassword
cdoSendUserName http://schemas.microsoft.com/cdo/configuration/sendusername
cdoSendUserReplyEmailAddress http://schemas.microsoft.com/cdo/configuration/senduserreplyemailaddress
cdoSendUsingMethod http://schemas.microsoft.com/cdo/configuration/sendusing
cdoSMTPAccountName http://schemas.microsoft.com/cdo/configuration/smtpaccountname
cdoSMTPAuthenticate http://schemas.microsoft.com/cdo/configuration/smtpauthenticate
cdoSMTPConnectionTimeout http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout
cdoSMTPServer http://schemas.microsoft.com/cdo/configuration/smtpserver
cdoSMTPServerPickupDirectory http://schemas.microsoft.com/cdo/configuration/smtpserverpickupdirectory
cdoSMTPServerPort http://schemas.microsoft.com/cdo/configuration/smtpserverport
cdoSMTPUseSSL http://schemas.microsoft.com/cdo/configuration/smtpusessl
cdoURLGetLatestVersion http://schemas.microsoft.com/cdo/configuration/urlgetlatestversion
cdoURLProxyBypass http://schemas.microsoft.com/cdo/configuration/urlproxybypass
cdoURLProxyServer http://schemas.microsoft.com/cdo/configuration/urlproxyserver
cdoUseMessageResponseText http://schemas.microsoft.com/cdo/configuration/usemessageresponsetext

CdoSendUsing

VBA マクロ CDO メール

Name Value Description
cdoSendUsingPickup 1 Send the message by using the local SMTP service pickup directory.
cdoSendUsingPort 2 Send the message by using the network (SMTP over the network).

CdoProtocolsAuthentication

VBA マクロ CDO メール

Name Value Description
cdoAnonymous 0 Perform no authentication.
cdoBasic 1 Use the basic (clear text) authentication mechanism.
cdoNTLM 2 Use the NTLM authentication mechanism.

CdoCharset

VBA マクロ CDO メール

Constant Value
CdoBIG5 big5
CdoEUC_JP euc-jp
CdoEUC_KR euc-kr
CdoGB2312 gb2312
CdoISO_2022_JP iso-2022-jp
CdoISO_2022_KR iso-2022-kr
CdoISO_8859_1 iso-8859-1
CdoISO_8859_2 iso-8859-2
CdoISO_8859_3 iso-8859-3
CdoISO_8859_4 iso-8859-4
CdoISO_8859_5 iso-8859-5
CdoISO_8859_6 iso-8859-6
CdoISO_8859_7 iso-8859-7
CdoISO_8859_8 iso-8859-8
CdoISO_8859_9 iso-8859-9
cdoKOI8_R koi8-r
cdoShift_JIS shift-jis
CdoUS_ASCII us-ascii
CdoUTF_7 utf-7
CdoUTF_8 utf-8


上記以外にも多数の定数があります。
必要になる事は少ないとは思いますが、必要に応じて調べて使用して下さい。



同じテーマ「マクロVBA技術解説」の記事

VBAでのInternetExplorer自動操作

・VBEの参照設定 ・InternetExplorerの開始と終了 ・HTMLオブジェクトの操作 ・VBAでのInternetExplorer操作例 ・WEBクローリング&スクレイピングのサイト内参考ページ
VBAでのSQLの基礎(SQL:Structured Query Language)
・SQL文 ・SELECT文 ・SQLの学習について ・実践例
VBAで正規表現を利用する(RegExp)
・メタ文字 ・正規表現 ・正規表現RegExpの使い方 ・RegExpオブジェクト ・RegExpの使用例 ・RegExp関連のオブジェクト ・Execute(Matches,Match,SubMatches)の使用例 ・Replaceの使用例 ・先読み:肯定先読み、否定先読み ・正規表現の実践例
VBAでメール送信する(CDO:Microsoft Collaboration Data Objects)
VBAでのOutlook自動操作
・Outlookインスタンスの生成と、ログオン、全て送受信 ・Outlookを起動して指定フォルダーを表示 ・フォルダーの取得 ・メールの一覧を取得 ・メールを送信 ・メールを返信 ・最後に
ADO(ActiveX Data Objects)の使い方の要点
・データベースの種類 ・SQL(SQL:Structured Query Language) ・ADOを使う準備 ・ADOでのDB接続方法 ・ADODB.Recordsetの取得方法 ・ADODBのレコードセットの扱い方 ・ADODBのトランザクション処理 ・ADODB.Commandの使い方 ・VBA100本ノックでの実践例 ・最後に注意点等
特殊フォルダの取得(WScript.Shell,SpecialFolders)
・WScript.Shell ・SpecialFolders プロパティ ・WshShellのSpecialFoldersのマクロVBA使用例
参照設定、CreateObject、オブジェクト式の一覧
VBAでエクセル外のオブジェクトを使うときには、事前バインディングと遅延バインディング(実行時バインディング)の2通りがあります、この時それぞれ何を指定したらよいのか、指定する文字列が長いので結構探してしまうことが度々あります。そこで、自身の覚え書きとしての意味も含めて、参照設定、CreateObjectのclas…
VBAのスクレイピングを簡単楽にしてくれるSelenium
・SeleniumBasicのインストール ・VBEでの参照設定 ・WEBサイトを表示してみましょう ・Seleniumの基本的な使い方(株価情報を取得してみる) ・色々なパターンでのseleniumの使い方 ・色々組み合わせて目的の画面にたどり着きます ・elementをコレクションで取得する ・新規ページが開かれる場合 ・上手くいかない特殊な場合の対処方法 ・Seleniumの実践例例 ・最後に
VBA+SeleniumBasicで検索順位チェッカー作成
・シート構成 ・検索順位チェッカーのVBA全コード ・最後に
VBA+SeleniumBasicで検索順位チェッカー(改)
・シート構成 ・検索順位チェッカーのVBA全コード ・最後に


新着記事NEW ・・・新着記事一覧を見る

VBA10大躓きポイント(初心者が躓きやすいポイント)|VBA技術解説(2024-03-05)
テンキーのスクリーンキーボード作成|ユーザーフォーム入門(2024-02-26)
無効な前方参照か、コンパイルされていない種類への参照です。|エクセル雑感(2024-02-17)
初級脱出10問パック|VBA練習問題(2024-01-24)
累計を求める数式あれこれ|エクセル関数応用(2024-01-22)
複数の文字列を検索して置換するSUBSTITUTE|エクセル入門(2024-01-03)
いくつかの数式の計算中にリソース不足になりました。|エクセル雑感(2023-12-28)
VBAでクリップボードへ文字列を送信・取得する3つの方法|VBA技術解説(2023-12-07)
難しい数式とは何か?|エクセル雑感(2023-12-07)
スピらない スピル数式 スピらせる|エクセル雑感(2023-12-06)


アクセスランキング ・・・ ランキング一覧を見る

1.最終行の取得(End,Rows.Count)|VBA入門
2.RangeとCellsの使い方|VBA入門
3.セルのコピー&値の貼り付け(PasteSpecial)|VBA入門
4.繰り返し処理(For Next)|VBA入門
5.変数宣言のDimとデータ型|VBA入門
6.ブックを閉じる・保存(Close,Save,SaveAs)|VBA入門
7.並べ替え(Sort)|VBA入門
8.条件分岐(IF)|VBA入門
9.セルのクリア(Clear,ClearContents)|VBA入門
10.マクロとは?VBAとは?VBAでできること|VBA入門




このサイトがお役に立ちましたら「シェア」「Bookmark」をお願いいたします。


記述には細心の注意をしたつもりですが、
間違いやご指摘がありましたら、「お問い合わせ」からお知らせいただけると幸いです。
掲載のVBAコードは動作を保証するものではなく、あくまでVBA学習のサンプルとして掲載しています。
掲載のVBAコードは自己責任でご使用ください。万一データ破損等の損害が発生しても責任は負いません。



このサイトがお役に立ちましたら「シェア」「Bookmark」をお願いいたします。
本文下部へ