Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package su.vistar.email.server.sender;
- import java.util.Properties;
- import java.util.logging.Level;
- import javax.mail.Authenticator;
- import javax.mail.Message;
- import javax.mail.MessagingException;
- import javax.mail.PasswordAuthentication;
- import javax.mail.Session;
- import javax.mail.Transport;
- import javax.mail.internet.InternetAddress;
- import javax.mail.internet.MimeMessage;
- import su.vistar.email.server.exceptions.EmailSendException;
- import su.vistar.logging.LoggerManager;
- /**
- * Отправка писем по почте.
- *
- * @author hunter
- */
- public class EmailSender {
- /** Параметры настройки соединения с SMTP сервером. */
- private final Properties props;
- /** Сессия соединения с SMTP сервером */
- private Session mailSession;
- /** Логгер. */
- private static final LoggerManager log = new LoggerManager();
- /**
- * Конструктор.<br>
- * <br>
- * Используемые настройки:
- * <ul>
- * <li>mail.protocol = smtp - протокол отправки</li>
- * <li>mail.smtp.auth - необходимость авторизации</li>
- * <li>mail.smtp.host - адрес почтового сервера</li>
- * <li>mail.smtp.user - имя отправителя</li>
- * <li>mail.smtp.password - пароль отправителя</li>
- * <li>charset - используемая кодировка</li>
- * </ul>
- *
- * @param props настройки.
- */
- public EmailSender(Properties props) {
- this.props = props;
- mailSession = Session.getInstance(props, new SMTPAuthenticator());
- }
- /**
- * Отсылает электронное письмо на заданные адреса
- *
- * @param recipients список адресов, разделенных запятой.
- * @param subject тема письма
- * @param text текст письма
- *
- * @throws Exception
- */
- public void send(String recipients, String subject, String text) throws EmailSendException {
- Transport transport = null;
- try {
- transport = mailSession.getTransport();
- MimeMessage message = new MimeMessage(mailSession);
- // адрес отправителя
- message.setFrom(new InternetAddress(props.getProperty("mail.smtp.user")));
- // адрес назначения
- message.addRecipients(Message.RecipientType.TO, recipients);
- message.setSubject(subject, props.getProperty("charset"));
- message.setContent(text, "text/html; charset=" + props.getProperty("charset"));
- log.log(Level.FINEST, "Старт подключения к серверу");
- transport.connect();
- log.log(Level.FINEST, "Отправка письма по адресам {0}, тема: {1}, текст: {2}",
- recipients, subject, text);
- transport.sendMessage(message,
- message.getRecipients(Message.RecipientType.TO));
- log.log(Level.FINER, "Письмо отправлено на адреса {0}, тема: {1}",
- recipients, subject);
- } catch (Exception ex) {
- log.log(Level.WARNING, ex, "Отправка письма по адресам {0} не удалась", recipients);
- throw new EmailSendException(ex);
- } finally {
- if (transport != null) {
- try {
- transport.close();
- } catch (MessagingException ignore) {
- }
- }
- }
- }
- /**
- * Класс отвечающий за аутентификацию на почтовом сервере.
- * @author hunter
- *
- */
- private class SMTPAuthenticator extends Authenticator {
- @Override
- public PasswordAuthentication getPasswordAuthentication() {
- String username = props.getProperty("mail.smtp.user");
- String password = props.getProperty("mail.smtp.password");
- return new PasswordAuthentication(username, password);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement