LoginSignup
0
1

More than 3 years have passed since last update.

【VBA - 備忘録】メール送信

Posted at

初期設定

コードを書く前に、Outlookのアカウントを作り、OutlookのオブジェクトライブラリーをVBAに読み込む必要がある

以下は、Outlookのオブジェクトライブラリの読み込み方

(1)「ツール」から「参照設定」に進む
image.png
(2)参照設定で、Microsoft Outlook 16.0 Object Libraryを選択し、OKボタンをクリックする
image.png

MailItemオブジェクトの指定

まずは、変数Outlookオブジェクトを作成し、さらにそれに対して、変数MailItemオブジェクトを指定する

Sub SendEmail()
Dim OutlookObj As Outlook.Application
Dim MailItemObj As Outlook.MailItem

Set OutlookObj = New Outlook.Application
Set MailItemObj = OutlookObj.CreateItem(olMailItem)
End Sub

各設定

MailItemオブジェクトに対して宛先や本文などを設定する

Sub SendEmail()
Dim OutlookObj As Outlook.Application
Dim MailItemObj As Outlook.MailItem

Set OutlookObj = New Outlook.Application
Set MailItemObj = OutlookObj.CreateItem(olMailItem)

With MailItemObj
 .To = "メールの宛先"
 .Subject = "メールの件名"
 .Body = "メールの本文"
 .Send '送信動作
End With
End Sub

HTMLメールの設定方法

各MailItemオブジェクトに対して、HTMLメールを設定する

'Sub SendEmail() '既に説明済のコードはコメントアウトしています

'Dim OutlookObj As Outlook.Application
'Dim MailItemObj As Outlook.MailItem

'Set OutlookObj = New Outlook.Application
'Set MailItemObj = OutlookObj.CreateItem(olMailItem)

'With MailItemObj
' .To = "メールの宛先"
' .Subject = "メールの件名"
 .BodyFormat = olFormatHTML 'HTMLメールと設定
 .HTMLBody = "HTMLメールの本文" ' "<h1>Hello World</h1>" の様に、HTMLで書く
' .Send '送信動作
'End With
'End Sub

ファイルを添付する

ファイルを添付するには、ファイルまでのパスを作成し、それをMailItemオブジェクトに対して添付設定として加えます。

'Sub SendEmail() '既に説明済のコードはコメントアウトしています

'Dim OutlookObj As Outlook.Application
'Dim MailItemObj As Outlook.MailItem

'Set OutlookObj = New Outlook.Application
'Set MailItemObj = OutlookObj.CreateItem(olMailItem)

Dim attachmentPath As String
    attachmentPath = "C:\Desktop\attachment.pdf" 'ファイルまでのパスに応じて変える

'With MailItemObj
' .To = "メールの宛先"
' .Subject = "メールの件名"
' .BodyFormat = olFormatHTML 'HTMLメールと設定
' .HTMLBody = "HTMLメールの本文" ' "<h1>Hello World</h1>" の様に、HTMLで書く
 .Attachments.Add (attachmentPath)
' .Send '送信動作
'End With
'End Sub
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1