Advertisement
Guest User

Untitled

a guest
May 6th, 2019
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.79 KB | None | 0 0
  1. import java.util.Properties;
  2.  
  3. import javax.mail.Message;
  4. import javax.mail.MessagingException;
  5. import javax.mail.Multipart;
  6. import javax.mail.PasswordAuthentication;
  7. import javax.mail.Session;
  8. import javax.mail.Transport;
  9. import javax.mail.internet.InternetAddress;
  10. import javax.mail.internet.MimeBodyPart;
  11. import javax.mail.internet.MimeMessage;
  12. import javax.mail.internet.MimeMultipart;
  13.  
  14. public class MailFunctions {
  15.     public static Session session;
  16.  
  17.     public static void init() {
  18.         final String username = "emailAddress";
  19.         final String password = "emailPW";
  20.  
  21.         Properties props = new Properties();
  22.         props.put("mail.smtp.auth", "true");
  23.         props.put("mail.smtp.starttls.enable", "true");
  24.         props.put("mail.smtp.host", "smtp.gmail.com");
  25.         props.put("mail.smtp.port", "587");
  26.  
  27.         session = Session.getInstance(props, new javax.mail.Authenticator() {
  28.             protected PasswordAuthentication getPasswordAuthentication() {
  29.                 return new PasswordAuthentication(username, password);
  30.             }
  31.         });
  32.     }
  33.  
  34.     public static void sendMail(String toMail, String subject, String text) {
  35.         try {
  36.             Message message = new MimeMessage(session);
  37.             message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toMail));
  38.             message.setSubject(subject);
  39.  
  40.             MimeBodyPart messageBodyPart = new MimeBodyPart();
  41.             // Fill the message
  42.             messageBodyPart.setText(text, "UTF-8", "html");
  43.  
  44.             Multipart multipart = new MimeMultipart();
  45.             multipart.addBodyPart(messageBodyPart);
  46.  
  47.             // Put parts in message
  48.             message.setContent(multipart);
  49.  
  50.             Transport.send(message);
  51.  
  52.         } catch (MessagingException e) {
  53.             throw new RuntimeException(e);
  54.         }
  55.     }
  56. }
  57.  
  58. /* pom dependecny
  59.         <dependency>
  60.             <groupId>javax.mail</groupId>
  61.             <artifactId>mail</artifactId>
  62.             <version>1.4.7</version>
  63.         </dependency>
  64. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement