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 SendFileAttachmentOAuth2 { public static void main(String[] args) { // Email configuration final String username = "ShunYCheung@gmail.com"; // Your Gmail address // OAuth2 token (you'll need to obtain this separately through the Google OAuth flow) // This is not your password, but an access token obtained through OAuth2 authentication final String oauth2Token = "wijs04heid"; // 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.gmail.com"); props.put("mail.smtp.port", "587"); props.put("mail.smtp.auth.mechanisms", "XOAUTH2"); props.put("mail.smtp.auth.login.disable", "true"); props.put("mail.smtp.auth.plain.disable", "true"); // Create a custom authenticator for XOAUTH2 Authenticator authenticator = new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, oauth2Token); } }; // Create session with OAuth2 authentication Session session = Session.getInstance(props, authenticator); 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) { e.printStackTrace(); throw new RuntimeException(e); } } }