#!/bin/bash

# Requires mailsend v1.15 or newer.

# Parameters

SMTP='smtp.jcom.home.ne.jp'

# Data Collection

function bailout () if [[ ! $ANSWER ]]; then exit 1; fi

function conversion () {
    echo $ANSWER | sed 's/</\&lt;/g' | sed 's/>/\&gt;/g'
}

function get_address () {
    echo $ANSWER | sed 's/.*<\(.*\)>.*/\1/'
}

FROM=$(zenity --entry --title 'From' --text 'Name and email of sender')
ANSWER=$FROM; bailout; FROM_HTML=$(conversion);
NAME=$(echo $FROM | sed 's/ *<.*>//')
FROM=$(get_address)

TO=$(zenity --entry --title 'To' --text 'Email of recipient')
ANSWER=$TO; bailout; TO_HTML=$(conversion); TO=$(get_address)

SUBJECT=$(zenity --entry --title 'Subject' --text 'Subject of the message')
ANSWER=$SUBJECT; bailout

MESSAGE=$(zenity --text-info --editable --title 'Enter Message Text')

zenity --question --title 'Confirmation' \
    --text "Sending message\n\nFrom: $FROM_HTML\nTo: $TO_HTML\nSubject: $SUBJECT\n\n$MESSAGE"
if [[ $? == 1 ]]; then exit 1; fi

DOMAIN=$(echo $FROM | sed 's/^.*@\([^>]*\).*$/\1/')

# Send
echo "$MESSAGE" > msg.temp
mailsend -q -d "$DOMAIN" -smtp "$SMTP" -t "$TO" -f "$FROM" -name "$NAME" \
    -sub "$SUBJECT" -attach "msg.temp,text/plain,i"
if [[ $? == 0 ]]; then
    zenity --info --title 'Sent' --text 'Your message was sent.';
else
    zenity --error --text 'Your message was NOT sent.';
fi
rm -f msg.temp