서버 | OS/Linux - Shell Script

Send e-mail with attachment in shell environment.

가을타는넘 2024. 2. 1. 23:16

Tested(target) OSs :

  • Ubuntu
  • Arch Linux

Required packages :

  • msmtp (simple mail client that can support external smtp like Gmail, Naver etc.)
  • mutt (needs for file attachment)

1. Install package

  • Ubuntu :
apt-get install -y msmtp mutt
  • Arch Linux :
pacman -S msmtp mutt

 

2. Prepare shell environment

  • create a "~/.msmtprc" file for msmtp
    cat << EOF > ~/.msmtprc
    # Set default values for all following accounts.
    defaults
    auth           on
    tls            on
    tls_trust_file /etc/ssl/certs/ca-certificates.crt
    logfile        ~/.msmtp.log
    
    # Naver
    account naver
    host smtp.naver.com
    port 465
    tls_starttls off
    from fromuser@naver.com
    user fromuser
    password password-for-fromuser
    
    # Set a default account
    account default: naver
  • Create a rc file for mutt
cat << EOF > ~/.muttrc
set sendmail=/usr/bin/msmtp
set use_from=yes
set from=<e-mail address>
EOF

3. Send an e-mail with attachment

# Simple
echo -e "hello there username." | mutt -a file.zip -s "Test hello attachment" -- receiver-user-name@gmail.com

# HTML content
mutt -e "set content_type=text/html" receiver-user-name@gmail.com -a file.zip -s "Test hello attachment" < ~/emailbo
dy.html