Advertisement
Guest User

Untitled

a guest
Feb 9th, 2017
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.53 KB | None | 0 0
  1. package ro.utcn.ds.service;
  2.  
  3. import javax.mail.*;
  4. import javax.mail.internet.InternetAddress;
  5. import javax.mail.internet.MimeMessage;
  6. import java.util.Properties;
  7.  
  8. public class MailService {
  9.     final String username;
  10.     final String password;
  11.     final Properties props;
  12.  
  13.     public MailService(String username, String password) {
  14.         this.username = username;
  15.         this.password = password;
  16.  
  17.         props = new Properties();
  18.         props.put("mail.smtp.auth", "true");
  19.         props.put("mail.smtp.starttls.enable", "true");
  20.         props.put("mail.smtp.host", "smtp.gmail.com");
  21.         props.put("mail.smtp.port", "587");
  22.     }
  23.  
  24.     public void sendMail(String to, String subject, String content) {
  25.         Session session = Session.getInstance(props,
  26.                 new javax.mail.Authenticator() {
  27.                     protected PasswordAuthentication getPasswordAuthentication() {
  28.                         return new PasswordAuthentication(username, password);
  29.                     }
  30.                 });
  31.  
  32.         try {
  33.  
  34.             Message message = new MimeMessage(session);
  35.             message.setFrom(new InternetAddress(username));
  36.             message.setRecipients(Message.RecipientType.TO,
  37.                     InternetAddress.parse(to));
  38.             message.setSubject(subject);
  39.             message.setText(content);
  40.  
  41.             Transport.send(message);
  42.  
  43.             System.out.println("Mail sent.");
  44.         } catch (MessagingException e) {
  45.             e.printStackTrace();
  46.         }
  47.     }
  48.  
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement