// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.util.Properties;

import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;

public class Mail {
    public static void main(String[] args) {
        String[] type = new String[(args.length - 4) / 2];
        String[] content = new String[(args.length - 4) / 2];
        for(int i = 0; i < type.length; i++) {
            type[i] = args[4 + 2 * i + 1];
            content[i] = load(args[4 + 2 * i]);
        }
        sendMultipartEmail(args[0], args[1], args[2], args[3], type, content);
    }
    public static String load(String filename) {
        StringBuffer sb = new StringBuffer("");
        try {
            BufferedReader in = new BufferedReader(new FileReader(filename));
            String line;
            while((line = in.readLine()) != null) {
                sb.append(line);
                sb.append('\n');
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
    public static void sendMultipartEmail(String mailserver, String from, String to, String subject, String[] type, String[] content) {
        try {
            Properties props = System.getProperties();
            props.put("mail.smtp.host", mailserver);
            Session session = Session.getDefaultInstance(props, null);
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject(subject);
            MimeMultipart mpart = new MimeMultipart();
            for(int i = 0; i < type.length; i++) {
                MimeBodyPart onempart = new MimeBodyPart();
                onempart.setContent(content[i], type[i]);
                mpart.addBodyPart(onempart);
            }
            message.setContent(mpart);
            Transport.send(message);
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
