Advertisement
fahimkamal63

Class to sent mail from application

Sep 17th, 2019
1,370
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.24 KB | None | 0 0
  1. /**
  2.  * Class to sent mail from application
  3.  * Date : 17.09.19
  4.  * Last Modified: 17.09.19
  5.  */
  6. package Test;
  7.  
  8. import java.util.Properties;
  9. import java.util.logging.Level;
  10. import java.util.logging.Logger;
  11. import javax.mail.Authenticator;
  12. import javax.mail.Message;
  13. import javax.mail.MessagingException;
  14. import javax.mail.PasswordAuthentication;
  15. import javax.mail.Session;
  16. import javax.mail.Transport;
  17. import javax.mail.internet.AddressException;
  18. import javax.mail.internet.InternetAddress;
  19. import javax.mail.internet.MimeMessage;
  20.  
  21. /**
  22.  *
  23.  * @author Fahim
  24.  */
  25. public class JavaMail {
  26.     public static void sendMail(String recepient) throws MessagingException{
  27.         System.out.println("Preparing to sent email");
  28.         Properties properties = new Properties();
  29.         properties.put("mail.smtp.auth", "true");
  30.         properties.put("mail.smtp.starttls.enable", "true");
  31.         properties.put("mail.smtp.host", "smtp.gmail.com");
  32.         properties.put("mail.smtp.port", "587");
  33.  
  34.         String myAccountEmail = "XXX@gmail.com";
  35.         String password = "xxxxx";
  36.        
  37.         Session session = Session.getInstance(properties,new Authenticator(){
  38.             protected PasswordAuthentication getPasswordAuthentication(){
  39.                
  40.                 return new PasswordAuthentication(myAccountEmail, password);
  41.             }
  42.         });
  43.        
  44.         Message massage = prepareMessage(session, myAccountEmail, recepient);
  45.         Transport.send(massage);
  46.         System.out.println("Email sent successfully");
  47.     }
  48.  
  49.     private static Message prepareMessage(Session session, String myAccountEmail, String recepient) {
  50.         try {
  51.             Message message = new MimeMessage(session);
  52.             message.setFrom(new InternetAddress(myAccountEmail));
  53.             message.setRecipient(Message.RecipientType.TO, new InternetAddress(recepient));
  54.             message.setSubject("My first Email from java app");
  55.             message.setText("Hey there, \nThis a automated Email. Created by the application. \n regards from Fahim");
  56.             return message;
  57.         } catch (Exception ex) {
  58.             Logger.getLogger(JavaMail.class.getName()).log(Level.SEVERE, null, ex);
  59.         }
  60.         return null;
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement