Posted at

Macでコマンドラインからメール送信


はじめに

コマンドライン(Bashスクリプト)からメール送信がしたくなったため、

方法を調べてみました。


メール送信スクリプト

今回はAppleScriptを使って送付しています。

初回実行時は、TerminalやiTerm2から実行する権限付与の確認ダイアログが出るかもしれません。


Outlookで送る場合

添付ファイルとCCもつけてます。

#!/bin/bash

FileName="/Users/foo/Desktop/bar.txt"
RecipientMail="foobar@example.com"
MyMail="hoge@example.com"

# Send filec result via Outlook
osascript <<EOF
set theAttachment to "
$FileName"
set theAttachment to theAttachment as POSIX file--convert to posix file
set theRecipient to "
$RecipientMail"
set theCCRecipient to "
$MyMail"
set theSubject to "タイトル"
set theContent to "foobar様
\r\rこんにちは\rファイルも添付します。\r\rhoge"

tell application "Microsoft Outlook"
set theMessage to make new outgoing message with properties {subject:theSubject, plain text content:theContent}
make new recipient at theMessage with properties {email address:{address:theRecipient}}
make new recipient at beginning of theMessage with properties {email address:{address:theCCRecipient}, type:cc recipient type}
tell theMessage--tell theMessage (not theContent) to add the attachment
make new attachment with properties {file:theAttachment}
end tell
send theMessage
end tell
EOF


Mail.appで送る場合

若干構文が違います。

CCの仕方はまだ分からず。

#!/bin/bash

# Mail app
osascript <<EOF
set recipientName to "foobar"
set recipientAddress to "foobar@example.com"
set theSubject to "Test Message"
set theContent to "Mail
\rtest"
set theAttachment to "/Users/hoge/dummy.txt"
set theAttachment to theAttachment as POSIX file--convert to posix file

tell application "Mail"
set theMessage to make new outgoing message with properties {subject:theSubject, content:theContent, visible:true}
tell theMessage
make new to recipient with properties {name:recipientName, address:recipientAddress}
make new attachment with properties {file name:theAttachment as alias}
end tell
end tell
EOF