/**************************************************************************************************
* NOTICE OF COPYRIGHT AND OWNERSHIP OF SOFTWARE:
*
* Copyright (c) 1997-2016 Flexera Software LLC. All Rights Reserved.
*
**************************************************************************************************/
package alerter;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/** This class manage email formatting and sending */
public class Email {
    public Email(String server, int port, String user, String password,
                 String fromAddress, String toAddress) {
        this.server = server;
        this.user = user;
        this.password = password;
        this.fromAddress = fromAddress;
        this.toAddress = toAddress;

        // Set the host smtp address
        props = new Properties();
        props.put("mail.smtp.host", server);
        props.put("mail.smtp.port", new Integer(port).toString());
    }
    
    public void send(String title, String description, String level,
                     String timestamp) {
        
        try {
            // get the default Session
            Session session = Session.getDefaultInstance(props, null);

            // create a message
            Message msg = new MimeMessage(session);

            // set the from and to address
            InternetAddress addressFrom = new InternetAddress(fromAddress);
            msg.setFrom(addressFrom);

            InternetAddress addressTo = new InternetAddress(toAddress);
            msg.addRecipient(Message.RecipientType.TO, addressTo);

            // Setting the Subject and Content Type
            msg.setSubject(title);
            msg.setContent(description, "text/plain");
            if (user != null) {
                Transport transport = session.getTransport("smtp");
                transport.connect(server, user, password);
                msg.saveChanges(); // don't forget this
                transport.sendMessage(msg, msg.getAllRecipients());
                transport.close();
            } else
                Transport.send(msg);
        }
        catch (Exception e) {
            System.out.println("Problem sending email: "+e);
        }
    }
    
    private String server;
    private Properties props;
    private String user;
    private String password;
    private String fromAddress;
    private String toAddress;
}
