非IT企業に勤める中年サラリーマンのIT日記

非IT企業でしかもITとは全く関係ない部署にいる中年エンジニア。唯一の趣味がプログラミングという”自称”プログラマー。

【Outlook/VBA】自動メール作成と画像挿入の方法

   

Outlookでの定型メール作成や画像挿入を自動化したい場合、VBAマクロを活用することで効率化できます。特にメール本文内に指定フォルダの画像を自動で追加する機能は便利です。

この記事では、複数人の宛先指定も含めOutlookで自動メールを作成するマクロの実装手順を解説します。手動操作を最小限にしメール作成の手間を減らす方法を確認しましょう。

Sub CreateMailWithImagesAndRecipients()
    Dim olApp As Object
    Dim olMail As Object
    Dim folderPath As String
    Dim imgFile As String
    Dim bodyText As String
    Dim imgCount As Integer
    Dim toRecipients As String
    Dim ccRecipients As String
    Dim recipient As Variant

    ' Outlookアプリケーションを取得
    Set olApp = CreateObject("Outlook.Application")
    Set olMail = olApp.CreateItem(0)

    ' 宛先とCCのリストを設定(カンマ区切り)
    toRecipients = "example1@example.com, example2@example.com"  ' Toに追加するアドレス
    ccRecipients = "example3@example.com, example4@example.com"  ' CCに追加するアドレス

    ' Toの宛先を追加
    For Each recipient In Split(toRecipients, ",")
        olMail.Recipients.Add Trim(recipient)
    Next recipient

    ' CCの宛先を追加
    For Each recipient In Split(ccRecipients, ",")
        With olMail.Recipients.Add(Trim(recipient))
            .Type = 2  ' 1 = To, 2 = CC, 3 = BCC
        End With
    Next recipient

    ' フォルダパスを指定
    folderPath = "C:\Users\...\images\"
    imgFile = Dir(folderPath & "*.png")  ' jpgファイルを対象に設定(他の形式も必要なら適宜変更)

    ' メールの件名と初期本文を設定
    olMail.Subject = "自動作成メール"
    bodyText = "以下に画像を貼り付けます:<br><br>"

    ' 画像を挿入し、本文に追加
    imgCount = 0
    Do While imgFile <> ""
        imgCount = imgCount + 1
        bodyText = bodyText & "<img width='300' src='file://" & folderPath & imgFile & "'>" & "&nbsp;"
        imgFile = Dir  ' 次の画像を取得
    Loop
    
    olMail.HTMLBody = bodyText

    ' 本文を設定してメールを表示
    olMail.Display
End Sub
 

 

  • toRecipientsccRecipientsにそれぞれの宛先をカンマ区切りで設定してください。
  • Toの宛先はolMail.Recipients.Addで追加し、CCの宛先には.Type = 2を設定しています。BCCを追加したい場合は、.Type = 3とすることで実現できます。

実行するとこのような画像を貼り付けたメールが自動生成されます。

 

 

スポンサーリンク

 - Outlook, VBA