Advertisement
Guest User

Untitled

a guest
Sep 30th, 2017
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 4.22 KB | None | 0 0
  1. package su.vistar.email.server.sender;
  2.  
  3. import java.util.Properties;
  4. import java.util.logging.Level;
  5.  
  6. import javax.mail.Authenticator;
  7. import javax.mail.Message;
  8. import javax.mail.MessagingException;
  9. import javax.mail.PasswordAuthentication;
  10. import javax.mail.Session;
  11. import javax.mail.Transport;
  12. import javax.mail.internet.InternetAddress;
  13. import javax.mail.internet.MimeMessage;
  14.  
  15. import su.vistar.email.server.exceptions.EmailSendException;
  16. import su.vistar.logging.LoggerManager;
  17.  
  18. /**
  19.  * Отправка писем по почте.
  20.  *
  21.  * @author hunter
  22.  */
  23. public class EmailSender {
  24.  
  25.     /** Параметры настройки соединения с SMTP сервером. */
  26.     private final Properties props;
  27.     /** Сессия соединения с SMTP сервером */
  28.     private Session mailSession;
  29.     /** Логгер. */
  30.     private static final LoggerManager log = new LoggerManager();
  31.  
  32.     /**
  33.      * Конструктор.<br>
  34.      * <br>
  35.      * Используемые настройки:
  36.      * <ul>
  37.      * <li>mail.protocol = smtp - протокол отправки</li>
  38.      * <li>mail.smtp.auth - необходимость авторизации</li>
  39.      * <li>mail.smtp.host - адрес почтового сервера</li>
  40.      * <li>mail.smtp.user - имя отправителя</li>
  41.      * <li>mail.smtp.password - пароль отправителя</li>
  42.      * <li>charset - используемая кодировка</li>
  43.      * </ul>
  44.      *
  45.      * @param props настройки.
  46.      */
  47.     public EmailSender(Properties props) {
  48.         this.props = props;
  49.  
  50.         mailSession = Session.getInstance(props, new SMTPAuthenticator());
  51.     }
  52.  
  53.     /**
  54.      * Отсылает электронное письмо на заданные адреса
  55.      *
  56.      * @param recipients список адресов, разделенных запятой.
  57.      * @param subject тема письма
  58.      * @param text текст письма
  59.      *
  60.      * @throws Exception
  61.      */
  62.     public void send(String recipients, String subject, String text) throws EmailSendException {
  63.         Transport transport = null;
  64.         try {
  65.             transport = mailSession.getTransport();
  66.             MimeMessage message = new MimeMessage(mailSession);
  67.  
  68.             // адрес отправителя
  69.             message.setFrom(new InternetAddress(props.getProperty("mail.smtp.user")));
  70.             // адрес назначения
  71.             message.addRecipients(Message.RecipientType.TO, recipients);
  72.             message.setSubject(subject, props.getProperty("charset"));
  73.             message.setContent(text, "text/html; charset=" + props.getProperty("charset"));
  74.  
  75.             log.log(Level.FINEST, "Старт подключения к серверу");
  76.             transport.connect();
  77.             log.log(Level.FINEST, "Отправка письма по адресам {0}, тема: {1}, текст: {2}",
  78.                     recipients, subject, text);
  79.             transport.sendMessage(message,
  80.                     message.getRecipients(Message.RecipientType.TO));
  81.             log.log(Level.FINER, "Письмо отправлено на адреса {0}, тема: {1}",
  82.                     recipients, subject);
  83.         } catch (Exception ex) {
  84.             log.log(Level.WARNING, ex, "Отправка письма по адресам {0} не удалась", recipients);
  85.             throw new EmailSendException(ex);
  86.         } finally {
  87.             if (transport != null) {
  88.                 try {
  89.                     transport.close();
  90.                 } catch (MessagingException ignore) {
  91.                 }
  92.             }
  93.         }
  94.     }
  95.  
  96.     /**
  97.      * Класс отвечающий за аутентификацию на почтовом сервере.
  98.      * @author hunter
  99.      *
  100.      */
  101.     private class SMTPAuthenticator extends Authenticator {
  102.  
  103.         @Override
  104.         public PasswordAuthentication getPasswordAuthentication() {
  105.             String username = props.getProperty("mail.smtp.user");
  106.             String password = props.getProperty("mail.smtp.password");
  107.             return new PasswordAuthentication(username, password);
  108.         }
  109.     }
  110. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement