
/*
 *  Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
*/
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


/**
 *
 * @author Shyamant Hegde
 */
package oracle.javacloud.emailpunchout;

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

public class JavaMail {

    /**
     * @param args the command line arguments
     */

    static String msgText = "Default Message";
    static String smtpHost;
    static String smtpPort;
    static String uname;
    static String pwd;
    static String rnames;
   // static String replyTo;
    static String subject;
    public JavaMail(String msgText, String smtpHost, String smtpPort, String uname, String rnames, String sub) {
        this.msgText = msgText;
        this.smtpHost = smtpHost;
        this.smtpPort = smtpPort;
        this.uname = uname;
        this.rnames = rnames;
        this.subject = sub;
//	this.replyTo = replyTo;
    }

    public static String service(String args) {

        System.out.println("JavaMail.service() method called");
        if (args.isEmpty()) {
	    return "Password field cannot be empty.Please provide the right password for the Password field.";
	}
	if (rnames.isEmpty()) {
	    return "Recipients field is empty.Please provide a value for the Recipients field.";
	}if (uname.isEmpty()) {
	    return "Username field cannot be empty.Please provide right username for the Username field.";
	}
        final String pwd = args;

	// create some properties and get the default Session
	Properties props = new Properties();
        props.put("mail.smtp.starttls.enable","true");
        props.put("mail.smtp.port", smtpPort);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        boolean debug = true;

        if (debug) props.put("mail.debug", true);
        
	Session session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(uname,
            pwd);
        }
        });
	session.setDebug(true);	
	try {

            	String[] recipientList = rnames.split(",");
		InternetAddress[] recipientAddress = new InternetAddress[recipientList.length];
		int counter = 0;
		for (String recipient : recipientList) {
    			recipientAddress[counter] = new InternetAddress(recipient.trim());
    			counter++;
		}
	    MimeMessage msg = new MimeMessage(session);
	    msg.setFrom(new InternetAddress(uname));
	    msg.setRecipients(Message.RecipientType.TO, rnames);
	    msg.setSubject(subject);
	    msg.setSentDate(new Date());
	    msg.setText(msgText);
            //msg.setReplyTo(InternetAddress.parse(replyTo));
            Transport transport = session.getTransport("smtp");
            transport.connect(uname, pwd);
//          Using authentication in an instance of Transport class instead of session
            transport.sendMessage(msg, recipientAddress);
                    
            return "E-mail successfully delivered";
        } catch (MessagingException mex) {
	    System.out.println("\n--Exception handling in JavaMail.java");
	    String errorMessage;
	    mex.printStackTrace();
	    	if(mex.getMessage().contains("x-oracle-HttpRequestId was not provided")){
			return "x-oracle-HttpRequestId was not provided";
		}else if(mex.getMessage().contains("No recipient found in the preformatted email")){
			return "No recipient found in the preformatted email";
		}else if(mex.getMessage().contains("request-id-already-exist")){
			return "x-oracle-HttpRequestId already exist for a email record.";
		}else if(mex.getMessage().contains("access-denied")){
			return "Username/Password provided doesn't have privileges to send mails.Please provide proper credentials.";
		}else if(mex.getMessage().contains("limit-exceeded")){
			return "Limit for the day for this account has exceeded.Please wait for 24 hours before trying again.";
		}else if(mex.getMessage().contains("Invalid Addresses")){
			return "Invalid addresses in the Recipient List.Provide valid e-mail addresses with format adhering to message/rfc822 standards.";
		}else if(mex.getMessage().contains("unexpected-exception")){
			return "Unexpected error has occurred at the server side.Please refer logs for more details";
		}else if(mex.getMessage().contains("The username/password provided is not correct")){
			return "Username/Password is not valid.Please provide proper credentials.";
		}else if(mex.getMessage().contains("The base URL is either not set")){
			return "The Java Mail API based e-mail punchout is not enabled.";
		}else if(mex.getMessage().contains("Error 500--Internal Server Error")){
			return "The server encountered an unexpected condition which prevented it from fulfilling the request.";
		}else {
			return "Mail Sending failed due to an unknown error.Refer Logs for more details";
    	    	}
	}
    }
}
