Search in sources :

Example 81 with Session

use of javax.mail.Session in project nhin-d by DirectProject.

the class SmtpMailClient method mail.

/*
     * (non-Javadoc)
     * 
     * @see org.nhind.xdm.MailClient#postMail(org.nhindirect.xd.common.DirectMessage, java.lang.String)
     */
public void mail(DirectMessage message, String messageId, String suffix) throws MessagingException {
    boolean debug = false;
    java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
    // Set the host SMTP address
    Properties props = new Properties();
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", hostname);
    props.put("mail.smtp.auth", "true");
    Authenticator auth = new SMTPAuthenticator();
    Session session = Session.getInstance(props, auth);
    session.setDebug(debug);
    InternetAddress addressFrom = new InternetAddress(message.getSender());
    InternetAddress[] addressTo = new InternetAddress[message.getReceivers().size()];
    int i = 0;
    for (String recipient : message.getReceivers()) {
        addressTo[i++] = new InternetAddress(recipient);
    }
    // Build message object
    mmessage = new MimeMessage(session);
    mmessage.setFrom(addressFrom);
    mmessage.setRecipients(Message.RecipientType.TO, addressTo);
    mmessage.setSubject(message.getSubject());
    mailBody = new MimeMultipart();
    mainBody = new MimeBodyPart();
    mainBody.setDataHandler(new DataHandler(message.getBody(), "text/plain"));
    mailBody.addBodyPart(mainBody);
    try {
        mimeAttach = new MimeBodyPart();
        mimeAttach.attachFile(message.getDirectDocuments().toXdmPackage(messageId).toFile());
    } catch (IOException e) {
        throw new MessagingException("Unable to create/attach xdm zip file", e);
    }
    mailBody.addBodyPart(mimeAttach);
    mmessage.setContent(mailBody);
    Transport.send(mmessage);
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) MessagingException(javax.mail.MessagingException) DataHandler(javax.activation.DataHandler) IOException(java.io.IOException) Properties(java.util.Properties) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) MimeBodyPart(javax.mail.internet.MimeBodyPart) Authenticator(javax.mail.Authenticator) Session(javax.mail.Session)

Example 82 with Session

use of javax.mail.Session in project Axe by DongyuCai.

the class SimpleMailSender method sendTextMail.

/**
	 * 以文本格式发送邮件
	 * 
	 * @param mailInfo
	 *            待发送的邮件的信息
	 */
public static boolean sendTextMail(MailSenderInfo mailInfo) {
    // 判断是否需要身份认证
    MyAuthenticator authenticator = null;
    Properties pro = mailInfo.getProperties();
    if (mailInfo.isValidate()) {
        // 如果需要身份认证,则创建一个密码验证器
        authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
    }
    // 根据邮件会话属性和密码验证器构造一个发送邮件的session
    Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
    try {
        // 根据session创建一个邮件消息
        Message mailMessage = new MimeMessage(sendMailSession);
        // 创建邮件发送者地址
        Address from = new InternetAddress(mailInfo.getFromAddress());
        // 设置邮件消息的发送者
        mailMessage.setFrom(from);
        // 创建邮件的接收者地址,并设置到邮件消息中
        Address to = new InternetAddress(mailInfo.getToAddress());
        mailMessage.setRecipient(Message.RecipientType.TO, to);
        // 设置邮件消息的主题
        mailMessage.setSubject(mailInfo.getSubject());
        // 设置邮件消息发送的时间
        mailMessage.setSentDate(new Date());
        // 设置邮件消息的主要内容
        String mailContent = mailInfo.getContent();
        mailMessage.setText(mailContent);
        // 发送邮件
        Transport.send(mailMessage);
        return true;
    } catch (MessagingException ex) {
        ex.printStackTrace();
    }
    return false;
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) Address(javax.mail.Address) InternetAddress(javax.mail.internet.InternetAddress) MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) Properties(java.util.Properties) Date(java.util.Date) Session(javax.mail.Session)

Example 83 with Session

use of javax.mail.Session in project oxCore by GluuFederation.

the class MailService method sendMail.

public boolean sendMail(SmtpConfiguration mailSmtpConfiguration, String from, String to, String subject, String message) {
    if (mailSmtpConfiguration == null) {
        log.error("Failed to send message from '{0}' to '{1}' because the SMTP configuration isn't valid!", from, to);
        return false;
    }
    log.debug("Host name: " + mailSmtpConfiguration.getHost() + ", port: " + mailSmtpConfiguration.getPort() + ", connection time out: " + this.connectionTimeout);
    String mailFrom = from;
    if (StringHelper.isEmpty(mailFrom)) {
        mailFrom = mailSmtpConfiguration.getFromEmailAddress();
    }
    Properties props = new Properties();
    props.put("mail.smtp.host", mailSmtpConfiguration.getHost());
    props.put("mail.smtp.port", mailSmtpConfiguration.getPort());
    props.put("mail.from", mailFrom);
    props.put("mail.smtp.connectiontimeout", this.connectionTimeout);
    props.put("mail.smtp.timeout", this.connectionTimeout);
    if (mailSmtpConfiguration.isRequiresSsl()) {
        props.put("mail.smtp.socketFactory.port", mailSmtpConfiguration.getPort());
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    }
    Session session = null;
    if (mailSmtpConfiguration.isRequiresAuthentication()) {
        props.put("mail.smtp.auth", "true");
        final String userName = mailSmtpConfiguration.getUserName();
        final String password = mailSmtpConfiguration.getPasswordDecrypted();
        session = Session.getInstance(props, new javax.mail.Authenticator() {

            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userName, password);
            }
        });
    } else {
        Session.getInstance(props, null);
    }
    MimeMessage msg = new MimeMessage(session);
    try {
        msg.setFrom(new InternetAddress(mailFrom));
        msg.setRecipients(Message.RecipientType.TO, to);
        msg.setSubject(subject, "UTF-8");
        msg.setSentDate(new Date());
        msg.setText(message + "\n", "UTF-8");
        Transport.send(msg);
    } catch (MessagingException ex) {
        log.error("Failed to send message", ex);
        return false;
    }
    return true;
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) Properties(java.util.Properties) Date(java.util.Date) Session(javax.mail.Session) PasswordAuthentication(javax.mail.PasswordAuthentication)

Example 84 with Session

use of javax.mail.Session in project oxTrust by GluuFederation.

the class MailUtils method sendMail.

public void sendMail(String from, String to, String subject, String message) throws MessagingException {
    log.debug("HostName: " + this.hostName + " Port: " + this.port + " ConnectionTimeOut: " + this.connectionTimeout);
    log.debug("UserName: " + this.userName + " Password: " + this.password);
    Properties props = new Properties();
    props.put("mail.smtp.host", this.hostName);
    props.put("mail.smtp.port", this.port);
    props.put("mail.from", from);
    props.put("mail.smtp.connectiontimeout", this.connectionTimeout);
    props.put("mail.smtp.timeout", this.connectionTimeout);
    props.put("mail.debug", true);
    props.put("mail.transport.protocol", "smtp");
    if (requiresSsl) {
        // props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.starttls.enable", true);
    //			props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    }
    Session session = null;
    if (requiresAuthentication) {
        props.put("mail.smtp.auth", "true");
        final String userName = this.userName;
        final String password = this.password;
        session = Session.getInstance(props, new javax.mail.Authenticator() {

            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userName, password);
            }
        });
    } else {
        session = Session.getInstance(props, null);
    }
    MimeMessage msg = new MimeMessage(session);
    msg.setFrom();
    msg.setRecipients(Message.RecipientType.TO, to);
    msg.setSubject(subject);
    msg.setSentDate(new Date());
    msg.setText(message + "\n");
    Transport.send(msg);
}
Also used : MimeMessage(javax.mail.internet.MimeMessage) Properties(java.util.Properties) Date(java.util.Date) Session(javax.mail.Session) PasswordAuthentication(javax.mail.PasswordAuthentication)

Example 85 with Session

use of javax.mail.Session in project midpoint by Evolveum.

the class MailTransport method send.

@Override
public void send(Message mailMessage, String transportName, Event event, Task task, OperationResult parentResult) {
    OperationResult result = parentResult.createSubresult(DOT_CLASS + "send");
    result.addCollectionOfSerializablesAsParam("mailMessage recipient(s)", mailMessage.getTo());
    result.addParam("mailMessage subject", mailMessage.getSubject());
    SystemConfigurationType systemConfiguration = NotificationFunctionsImpl.getSystemConfiguration(cacheRepositoryService, new OperationResult("dummy"));
    if (systemConfiguration == null || systemConfiguration.getNotificationConfiguration() == null || systemConfiguration.getNotificationConfiguration().getMail() == null) {
        String msg = "No notifications are configured. Mail notification to " + mailMessage.getTo() + " will not be sent.";
        LOGGER.warn(msg);
        result.recordWarning(msg);
        return;
    }
    //		if (mailConfigurationType == null) {
    MailConfigurationType mailConfigurationType = systemConfiguration.getNotificationConfiguration().getMail();
    //		}
    String redirectToFile = mailConfigurationType.getRedirectToFile();
    if (redirectToFile != null) {
        try {
            TransportUtil.appendToFile(redirectToFile, formatToFile(mailMessage));
            result.recordSuccess();
        } catch (IOException e) {
            LoggingUtils.logException(LOGGER, "Couldn't write to mail redirect file {}", e, redirectToFile);
            result.recordPartialError("Couldn't write to mail redirect file " + redirectToFile, e);
        }
        return;
    }
    if (mailConfigurationType.getServer().isEmpty()) {
        String msg = "Mail server(s) are not defined, mail notification to " + mailMessage.getTo() + " will not be sent.";
        LOGGER.warn(msg);
        result.recordWarning(msg);
        return;
    }
    long start = System.currentTimeMillis();
    String defaultFrom = mailConfigurationType.getDefaultFrom() != null ? mailConfigurationType.getDefaultFrom() : "nobody@nowhere.org";
    for (MailServerConfigurationType mailServerConfigurationType : mailConfigurationType.getServer()) {
        OperationResult resultForServer = result.createSubresult(DOT_CLASS + "send.forServer");
        final String host = mailServerConfigurationType.getHost();
        resultForServer.addContext("server", host);
        resultForServer.addContext("port", mailServerConfigurationType.getPort());
        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", host);
        if (mailServerConfigurationType.getPort() != null) {
            properties.setProperty("mail.smtp.port", String.valueOf(mailServerConfigurationType.getPort()));
        }
        MailTransportSecurityType mailTransportSecurityType = mailServerConfigurationType.getTransportSecurity();
        boolean sslEnabled = false, starttlsEnable = false, starttlsRequired = false;
        if (mailTransportSecurityType != null) {
            switch(mailTransportSecurityType) {
                case STARTTLS_ENABLED:
                    starttlsEnable = true;
                    break;
                case STARTTLS_REQUIRED:
                    starttlsEnable = true;
                    starttlsRequired = true;
                    break;
                case SSL:
                    sslEnabled = true;
                    break;
            }
        }
        properties.put("mail.smtp.ssl.enable", "" + sslEnabled);
        properties.put("mail.smtp.starttls.enable", "" + starttlsEnable);
        properties.put("mail.smtp.starttls.required", "" + starttlsRequired);
        if (Boolean.TRUE.equals(mailConfigurationType.isDebug())) {
            properties.put("mail.debug", "true");
        }
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Using mail properties: ");
            for (Object key : properties.keySet()) {
                if (key instanceof String && ((String) key).startsWith("mail.")) {
                    LOGGER.debug(" - " + key + " = " + properties.get(key));
                }
            }
        }
        task.recordState("Sending notification mail via " + host);
        Session session = Session.getInstance(properties);
        try {
            MimeMessage mimeMessage = new MimeMessage(session);
            String from = mailMessage.getFrom() != null ? mailMessage.getFrom() : defaultFrom;
            mimeMessage.setFrom(new InternetAddress(from));
            for (String recipient : mailMessage.getTo()) {
                mimeMessage.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(recipient));
            }
            for (String recipientCc : mailMessage.getCc()) {
                mimeMessage.addRecipient(javax.mail.Message.RecipientType.CC, new InternetAddress(recipientCc));
            }
            for (String recipientBcc : mailMessage.getBcc()) {
                mimeMessage.addRecipient(javax.mail.Message.RecipientType.BCC, new InternetAddress(recipientBcc));
            }
            mimeMessage.setSubject(mailMessage.getSubject(), "utf-8");
            String contentType = mailMessage.getContentType();
            if (StringUtils.isEmpty(contentType)) {
                contentType = "text/plain; charset=UTF-8";
            }
            mimeMessage.setContent(mailMessage.getBody(), contentType);
            javax.mail.Transport t = session.getTransport("smtp");
            if (StringUtils.isNotEmpty(mailServerConfigurationType.getUsername())) {
                ProtectedStringType passwordProtected = mailServerConfigurationType.getPassword();
                String password = null;
                if (passwordProtected != null) {
                    try {
                        password = protector.decryptString(passwordProtected);
                    } catch (EncryptionException e) {
                        String msg = "Couldn't send mail message to " + mailMessage.getTo() + " via " + host + ", because the plaintext password value couldn't be obtained. Trying another mail server, if there is any.";
                        LoggingUtils.logException(LOGGER, msg, e);
                        resultForServer.recordFatalError(msg, e);
                        continue;
                    }
                }
                t.connect(mailServerConfigurationType.getUsername(), password);
            } else {
                t.connect();
            }
            t.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
            LOGGER.info("Message sent successfully to " + mailMessage.getTo() + " via server " + host + ".");
            resultForServer.recordSuccess();
            result.recordSuccess();
            long duration = System.currentTimeMillis() - start;
            task.recordState("Notification mail sent successfully via " + host + ", in " + duration + " ms overall.");
            task.recordNotificationOperation(NAME, true, duration);
            return;
        } catch (MessagingException e) {
            String msg = "Couldn't send mail message to " + mailMessage.getTo() + " via " + host + ", trying another mail server, if there is any";
            LoggingUtils.logException(LOGGER, msg, e);
            resultForServer.recordFatalError(msg, e);
            task.recordState("Error sending notification mail via " + host);
        }
    }
    LOGGER.warn("No more mail servers to try, mail notification to " + mailMessage.getTo() + " will not be sent.");
    result.recordWarning("Mail notification to " + mailMessage.getTo() + " could not be sent.");
    task.recordNotificationOperation(NAME, false, System.currentTimeMillis() - start);
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) MessagingException(javax.mail.MessagingException) MailConfigurationType(com.evolveum.midpoint.xml.ns._public.common.common_3.MailConfigurationType) MailServerConfigurationType(com.evolveum.midpoint.xml.ns._public.common.common_3.MailServerConfigurationType) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) IOException(java.io.IOException) Properties(java.util.Properties) MailTransportSecurityType(com.evolveum.midpoint.xml.ns._public.common.common_3.MailTransportSecurityType) MimeMessage(javax.mail.internet.MimeMessage) EncryptionException(com.evolveum.midpoint.prism.crypto.EncryptionException) SystemConfigurationType(com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType) ProtectedStringType(com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType) Session(javax.mail.Session)

Aggregations

Session (javax.mail.Session)110 MimeMessage (javax.mail.internet.MimeMessage)72 Properties (java.util.Properties)66 InternetAddress (javax.mail.internet.InternetAddress)49 MessagingException (javax.mail.MessagingException)47 Message (javax.mail.Message)31 Test (org.junit.Test)30 Transport (javax.mail.Transport)28 JMSession (com.zimbra.cs.util.JMSession)20 PasswordAuthentication (javax.mail.PasswordAuthentication)19 Date (java.util.Date)17 MimeBodyPart (javax.mail.internet.MimeBodyPart)16 MimeMultipart (javax.mail.internet.MimeMultipart)16 ZMimeMessage (com.zimbra.common.zmime.ZMimeMessage)15 IOException (java.io.IOException)15 SharedByteArrayInputStream (javax.mail.util.SharedByteArrayInputStream)15 Authenticator (javax.mail.Authenticator)12 Multipart (javax.mail.Multipart)11 NoSuchProviderException (javax.mail.NoSuchProviderException)10 BodyPart (javax.mail.BodyPart)9