Saturday 10 September 2022

Unix linux html email with attachment

 I gone through couple of sources and wrote the below code.

It works perfectly for me.

export ATTACHMENT=/x/project/Emp_Report.xlsx
EMAIL_BOUNDARY_STRING=Z${RANDOM}${RANDOM}${RANDOM}${RANDOM}

if [[ -f /x/project/Emp_Report.xlsx ]]; then
    echo "Employee Report exists !!"
    (
        echo "From: abc@gmail.com"
        echo "To: xyz@gmail.com"
        echo "cc: pqr@gmail.com"
        echo "Subject:Employee Report"
        echo "MIME-Version: 1.0"
        echo 'Content-Type: multipart/mixed; boundary="${EMAIL_BOUNDARY_STRING}"'
        echo '--${EMAIL_BOUNDARY_STRING}'
        
        echo "Content-Type: text/html"
        echo "Content-Disposition: inline"
        echo "<html>"
        echo "<body>"
        echo "<p>Hi Team,</p>"
        echo "<p>Please find the Employee details in attachment.</p>"
        echo "<p>In case of any queries, kindly reach out to 'abc@gmail.com'</p>"
        echo "<b>Regards,</b><br>"
        echo "Abc"
        echo "</body></html>"
        echo '--${EMAIL_BOUNDARY_STRING}'
    
        echo 'Content-Type: application/octet-stream; name="'$(basename $ATTACHMENT)'"'
        echo "Content-Transfer-Encoding: base64"
        echo 'Content-Disposition: attachment; filename="'$(basename $ATTACHMENT)'"'
        uuencode -m $ATTACHMENT $(basename $ATTACHMENT)
    
    ) |  /usr/sbin/sendmail -t