Skip to content
Send email from the command line

Send email from the command line

Sometimes you need to send an email from the console or from a bash script. Here are a few use cases.

  • mail – simple email: echo "BODY MESSAGE" | mail -s "Subject" rcpt@some-domain.com

  • mail – with attachment: echo "BODY MESSAGE" | mail -s "Subject" -a attachment.txt rcpt@some-domain.com

  • sendmail – simple email:

    sendmail email@some-domain.com <<EOF
    Subject: Test Subject
    From: test@some-domain.com
    
    Email body.
    EOF
  • sendmail – HTML content:

    sendmail email@some-domain.com <<EOF
    Subject: Test Subject
    From: test@some-domain.com
    MIME-Version: 1.0
    Content-Type: text/html
    
    <html>
      <head>
        <title>My email</title>
      </head>
      <body>
        <h2>Here will be your message body</h2>
      </body>
    </html>
    EOF
  • sendmail – HTML with an attached picture:

    mailpart="$(uuidgen)"
    sendmail -t <<EOM
    To: email@some-domain.com
    Subject: Test Subject
    From: test@some-domain.com
    MIME-Version: 1.0
    Content-Type: multipart/mixed; boundary="${mailpart}"
    
    --${mailpart}
    Content-Type: text/html; charset=ISO-8859-15
    Content-Transfer-Encoding: 7bit
    
    <html>
      <head>
        <title>My email</title>
      </head>
      <body>
        <img src="cid:part1.06090408.01060107" alt="">
      </body>
    </html>
    
    --${mailpart}
    Content-Type: image/png; name="filename.png"
    Content-Transfer-Encoding: base64
    Content-ID: <part1.06090408.01060107>
    Content-Disposition: inline; filename="filename.png"
    
    $(base64 /path/to/filename.png)
    --${mailpart}--
    EOM
  • sendmail – HTML with an embedded picture and a plain-text alternative:

    mailpart="$(uuidgen)"
    mailpartBody="$(uuidgen)"
    
    /usr/sbin/sendmail -t <<EOF
    Subject: Test Subject
    From: email@some-domain.com
    To: email@some-domain.com
    Content-Type: multipart/related; type="multipart/alternative"; boundary="${mailpart}"
    MIME-Version: 1.0
    
    --${mailpart}
    Content-Type: multipart/alternative; boundary="${mailpartBody}"
    
    --${mailpartBody}
    Content-Type: text/plain
    Content-Transfer-Encoding: 7bit
    
    Here we have message-body
    
    --${mailpartBody}
    Content-Type: text/html; charset="utf-8"
    Content-Transfer-Encoding: 7bit
    
    <html>
      <head>
        <title>My email</title>
      </head>
      <body>
        <h3>Here we have message-body</h3>
        <img src="cid:image.png@some-domain.com" alt="">
      </body>
    </html>
    
    --${mailpartBody}--
    
    --${mailpart}
    Content-ID: <image.png@some-domain.com>
    Content-Type: image/png; name=image.png
    Content-Disposition: inline; filename=image.png
    Content-Transfer-Encoding: base64
    
    $(base64 image.png)
    
    --${mailpart}--
    EOF
Last updated on