Newer
Older
marking / src / main / java / report / SendReport.java
package report;

import dao.MarkingProperties;
import dao.ResultDAO;
import jakarta.activation.FileDataSource;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import model.Student;
import org.simplejavamail.api.email.Email;
import org.simplejavamail.api.mailer.config.TransportStrategy;
import org.simplejavamail.email.EmailBuilder;
import org.simplejavamail.mailer.MailerBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Mark George <mark.george@otago.ac.nz>
 */
public class SendReport {

	private static String password = null;

	private static final Logger logger = LoggerFactory.getLogger(SendReport.class);

	public void sendReport(Student student, String reportFileName) {

		String assessment = MarkingProperties.assessmentDescription();
		String file = MarkingProperties.attachmentEmailName();

		String mName = MarkingProperties.markerName();
		String mEmail = MarkingProperties.markerEmail();
		String ccEmail = MarkingProperties.ccEmail();
		String mCode = MarkingProperties.paperCode();

		String message
			 = "Hi " + student.getFirstName() + ".\n"
			 + "\n"
			 + "Here is our feedback from marking your " + mCode + " " + assessment + " submission.  The feedback is in the attached PDF document.\n"
			 + "\n"
			 + "Cheers,\n"
			 + mName;

		Email email = EmailBuilder.startingBlank()
			 .from(mName, mEmail)
			 .to(student.getEmail())
			 .cc(ccEmail)
			 .withSubject(mCode + " " + assessment + " Result")
			 .withPlainText(message)
			 .withAttachment(file, new FileDataSource(reportFileName))
			 .buildEmail();

		try {

			String userName = MarkingProperties.smtpUserName();

			if (password == null && userName != null) {
				String result = getPassword("Staff E-Mail Password");
				if (result != null) {
					password = result;
				} else {
					System.out.println("Cancelled");
					return;
				}
			}

			TransportStrategy transport = TransportStrategy.SMTP;

			if (MarkingProperties.isTls()) {
				transport = TransportStrategy.SMTP_TLS;
			}

			MailerBuilder
				 .withSMTPServer(MarkingProperties.smtpHost(), MarkingProperties.smtpPort(), userName, password)
				 .withTransportStrategy(transport)
				 .buildMailer()
				 .sendMail(email);

			new ResultDAO().mailSent(student);

		} catch (Exception ex) {
			JOptionPane.showMessageDialog(null, "Error sending email - password wrong?", "Mail Error", JOptionPane.ERROR_MESSAGE);
			password = null;
			logger.error(ex.getLocalizedMessage(), ex);
		}

	}

	public static String getPassword(String prompt) {
		JPasswordField txtPasswd = new JPasswordField();
		int resp = JOptionPane.showConfirmDialog(null, txtPasswd, prompt,
			 JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
		if (resp == JOptionPane.OK_OPTION) {
			return new String(txtPasswd.getPassword());
		}
		return null;
	}

}