import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.*; import javax.mail.internet.*; import com.sun.mail.smtp.SMTPTransport; import java.util.Base64; public class EmailSender { public static void main(String[] args) { final String username = "cheung@emory.edu"; final String password = "Beta01234."; final String recipientEmail = "cheung@emory.edu"; final String filePath = "x"; Properties props = new Properties(); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.office365.com"); props.put("mail.smtp.port", "587"); props.put("mail.smtp.ssl.trust", "smtp.office365.com"); props.put("mail.smtp.auth.mechanisms", "XOAUTH2"); Session session = Session.getInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(username)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail)); message.setSubject("Email with Attachment"); MimeBodyPart textPart = new MimeBodyPart(); textPart.setText("Please find the attached file."); MimeBodyPart attachmentPart = new MimeBodyPart(); File file = new File(filePath); DataSource source = new FileDataSource(file); attachmentPart.setDataHandler(new DataHandler(source)); attachmentPart.setFileName(file.getName()); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(textPart); multipart.addBodyPart(attachmentPart); message.setContent(multipart); SMTPTransport transport = (SMTPTransport) session.getTransport("smtp"); transport.connect("smtp.office365.com", username, password); transport.sendMessage(message, message.getAllRecipients()); transport.close(); System.out.println("Email sent successfully!"); } catch (MessagingException e) { e.printStackTrace(); } } }