import java.util.Properties; import javax.mail.*; import javax.mail.internet.*; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.activation.DataHandler; import java.io.File; public class SendFileAttachment { public static void main(String[] args) { // Email configuration final String username = "ShunYCheung@gmail.com"; // Replace with your email final String password = "wijs04heid"; // Replace with your email password or app password // Recipient email String toEmail = "cheung@emory.edu"; // Replace with recipient email // SMTP properties Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.office365.com"); // Or your email provider's SMTP server props.put("mail.smtp.port", "587"); // Create session with authentication Session session = Session.getInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { // Create message Message message = new MimeMessage(session); message.setFrom(new InternetAddress(username)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail)); message.setSubject("File Attachment"); // Create the message body part BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText("Please find the attached file."); // Create multipart message Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // File attachment part messageBodyPart = new MimeBodyPart(); String filename = "x"; // The name of the file to attach File file = new File(filename); if (!file.exists()) { System.out.println("File does not exist: " + filename); return; } DataSource source = new FileDataSource(file); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); // Set the complete message parts message.setContent(multipart); // Send message System.out.println("Sending email with attachment..."); Transport.send(message); System.out.println("Email sent successfully!"); } catch (MessagingException e) { throw new RuntimeException(e); } } }