I am trying to send an email using Java and Gmail. I have stored my files on the cloud and the stored files I want to send as an attachment to my email.
It should add those files to this mail and not links of those files.
How I can send such attachments?
attachFile(new File("path/to/file")); We've now two MimeBodyPart objects for one mail Session. So we need to create one MimeMultipart object and then add both the MimeBodyPart objects into it: Multipart multipart = new MimeMultipart(); multipart.
To send an e-mail using your Java Application is simple enough but to start with you should have JavaMail API and Java Activation Framework (JAF) installed on your machine. You can download latest version of JavaMail (Version 1.2) from Java's standard website. You can download latest version of JAF (Version 1.1.
Working code, I have used Java Mail 1.4.7 jar
import java.util.Properties; import javax.activation.*; import javax.mail.*; public class MailProjectClass { public static void main(String[] args) { final String username = "[email protected]"; final String password = "your.password"; 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"); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress("[email protected]")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]")); message.setSubject("Testing Subject"); message.setText("PFA"); MimeBodyPart messageBodyPart = new MimeBodyPart(); Multipart multipart = new MimeMultipart(); String file = "path of file to be attached"; String fileName = "attachmentName"; DataSource source = new FileDataSource(file); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(fileName); multipart.addBodyPart(messageBodyPart); message.setContent(multipart); System.out.println("Sending"); Transport.send(message); System.out.println("Done"); } catch (MessagingException e) { e.printStackTrace(); } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With