Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import javax.activation.DataHandler;
- import javax.activation.DataSource;
- import javax.activation.FileDataSource;
- import javax.mail.*;
- import javax.mail.internet.*;
- import java.io.File;
- import java.util.Properties;
- public class SendMail extends Thread {
- static Properties mailServerProperties;
- static Session getMailSession;
- static MimeMessage generateMailMessage;
- public SendMail(){
- super();
- }
- public void run(){
- try {
- // Step1
- System.out.println("\n 1st ===> setup Mail Server Properties..");
- mailServerProperties = System.getProperties();
- mailServerProperties.put("mail.smtp.port", "587");
- mailServerProperties.put("mail.smtp.auth", "true");
- mailServerProperties.put("mail.smtp.starttls.enable", "true");
- System.out.println("Mail Server Properties have been setup successfully..");
- // Step2
- System.out.println("\n\n 2nd ===> get Mail Session..");
- getMailSession = Session.getInstance(mailServerProperties, new javax.mail.Authenticator() {
- protected PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication("mash.savenko@gmail.com", "ykmjmgnogaqqbnqa");
- }
- });
- generateMailMessage = new MimeMessage(getMailSession);
- generateMailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress("msav.post@gmail.com"));
- //generateMailMessage.addRecipient(Message.RecipientType.CC, new InternetAddress("test2@crunchify.com"));
- generateMailMessage.setSubject("Some files");
- String emailBody = "Body";
- generateMailMessage.setText(emailBody);
- MimeBodyPart messageBodyPart = new MimeBodyPart();
- Multipart multipart = new MimeMultipart();
- File folder = new File ("toSend");
- for (final File fileEntry : folder.listFiles()) {
- if (!fileEntry.isDirectory()) {
- String file = "toSend/" + fileEntry.getName();
- DataSource source = new FileDataSource(file);
- messageBodyPart.setDataHandler(new DataHandler(source));
- messageBodyPart.setFileName(file);
- multipart.addBodyPart(messageBodyPart);
- } else {
- System.out.println("/toSend folder contain another folders" );
- }
- }
- generateMailMessage.setContent(multipart);
- System.out.println("Mail Session has been created successfully...");
- // Step3
- System.out.println("\n\n 3rd ===> Get Session and Send mail");
- Transport transport = getMailSession.getTransport("smtp");
- // Enter your correct gmail UserID and Password
- // if you have 2FA enabled then provide App Specific Password
- transport.connect("smtp.gmail.com", "mash.savenko@gmail.com", "ykmjmgnogaqqbnqa");
- transport.sendMessage(generateMailMessage, generateMailMessage.getAllRecipients());
- transport.close();
- System.out.println("Done!");
- } catch (MessagingException e) {
- throw new RuntimeException(e);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement