Advertisement
Guest User

Untitled

a guest
Feb 28th, 2017
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.05 KB | None | 0 0
  1. import java.util.*;
  2. import javax.mail.*;
  3. import javax.mail.internet.*;
  4.  
  5. public class Main {
  6.    
  7.     private static String RECIPIENT = "fkhan@edmunds.com";
  8.  
  9.     public static void main(String[] args) {
  10.         String from = "khanfaizal017";
  11.         String pass = "changeme";
  12.         String[] to = { RECIPIENT }; // list of recipient email addresses
  13.         String subject = "Java send mail example";
  14.         String body = "Welcome to JavaMail!";
  15.  
  16.         sendFromGMail(from, pass, to, subject, body);
  17.     }
  18.  
  19.     private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
  20.         Properties props = System.getProperties();
  21.         String host = "smtp.gmail.com";
  22.         props.put("mail.smtp.starttls.enable", "true");
  23.         props.put("mail.smtp.host", host);
  24.         props.put("mail.smtp.user", from);
  25.         props.put("mail.smtp.password", pass);
  26.         props.put("mail.smtp.port", "587");
  27.         props.put("mail.smtp.auth", "true");
  28.  
  29.         Session session = Session.getDefaultInstance(props);
  30.         MimeMessage message = new MimeMessage(session);
  31.  
  32.         try {
  33.             message.setFrom(new InternetAddress(from));
  34.             InternetAddress[] toAddress = new InternetAddress[to.length];
  35.  
  36.             // To get the array of addresses
  37.             for( int i = 0; i < to.length; i++ ) {
  38.                 toAddress[i] = new InternetAddress(to[i]);
  39.             }
  40.  
  41.             for( int i = 0; i < toAddress.length; i++) {
  42.                 message.addRecipient(Message.RecipientType.TO, toAddress[i]);
  43.             }
  44.  
  45.             message.setSubject(subject);
  46.             message.setText(body);
  47.             Transport transport = session.getTransport("smtp");
  48.             transport.connect(host, from, pass);
  49.             transport.sendMessage(message, message.getAllRecipients());
  50.             transport.close();
  51.         }
  52.         catch (AddressException ae) {
  53.             ae.printStackTrace();
  54.         }
  55.         catch (MessagingException me) {
  56.             me.printStackTrace();
  57.         }
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement