Example usage for javax.mail Session getInstance

List of usage examples for javax.mail Session getInstance

Introduction

In this page you can find the example usage for javax.mail Session getInstance.

Prototype

public static Session getInstance(Properties props) 

Source Link

Document

Get a new Session object.

Usage

From source file:at.molindo.notify.channel.mail.DirectMailClient.java

protected Session createSmtpSession(String domain) throws MailException {
    try {//from  ww  w .j  a  v a  2  s.  co m
        final Properties props = new Properties();
        props.setProperty("mail.smtp.host", DnsUtils.lookupMailHosts(domain)[0]);
        props.setProperty("mail.smtp.port", "25");
        props.setProperty("mail.smtp.auth", "false");
        props.setProperty("mail.smtp.starttls.enable", Boolean.toString(getStartTLSEnabled()));

        // set proxy
        if (Boolean.TRUE.equals(getProxySet())) {
            props.setProperty("proxySet", "true");
            props.setProperty("socksProxyHost", getSocksProxyHost());
            props.setProperty("socksProxyPort", getSocksProxyPort());
        }

        if (getLocalHost() != null) {
            props.setProperty("mail.smtp.localhost", getLocalHost());
        }
        if (getLocalAddress() != null) {
            props.setProperty("mail.smtp.localaddress", getLocalAddress());
        }

        props.setProperty("mail.smtp.connectiontimeout", CONNECTION_TIMEOUT_MS);
        props.setProperty("mail.smtp.timeout", READ_TIMEOUT_MS);

        // props.put("mail.debug", "true");
        return Session.getInstance(props);
    } catch (NamingException e) {
        throw new MailException("can't lookup mail host: " + domain, e, true);
    }
}

From source file:org.xwiki.contrib.mail.internal.AbstractMailStore.java

/**
 * Creates appropriate javamail Store object.
 * //  w  ww .jav  a  2 s  . co m
 * @param debug
 * @return
 * @throws NoSuchProviderException
 */
protected Store getJavamailStore(boolean debug) throws NoSuchProviderException {
    Properties props = getStoreProperties();
    Session session = Session.getInstance(props);
    if (debug) {
        session.setDebug(true);
    }

    String url = getProvider() + ":" + getMailSource().getLocation();

    return session.getStore(new URLName(url));
}

From source file:org.jtalks.tests.jcommune.mail.mailtrap.MailtrapMail.java

private String tryToGetLink(String recipient) {
    Gson gson = new Gson();
    MessageDto[] messages;//from   w  ww  . ja va 2s. co  m
    String link = null;

    messages = gson.fromJson(MailtrapClient.getMessages(), MessageDto[].class);

    List<Metadata> metadataList = getMetadataList(messages);

    String id = NOT_FOUND_ID;
    DateTime createdAt = null;
    for (Metadata metadata : metadataList) {
        if (!recipient.equals(metadata.getRecipient())) {
            continue;
        }
        if (id.equals(NOT_FOUND_ID) || metadata.getDateTime().isAfter(createdAt)) {
            id = metadata.getId();
        }
    }
    if (id.equals(NOT_FOUND_ID)) {
        return link;
    }

    MessageDto messageDto = gson.fromJson(MailtrapClient.getMessage(id), MessageDto.class);

    try {
        String source = messageDto.getMessage().getSource();

        MimeMessage message = new MimeMessage(Session.getInstance(new Properties()),
                (new ByteArrayInputStream(source.getBytes())));
        Multipart multipart = (Multipart) message.getContent();
        Multipart multipart1 = (Multipart) multipart.getBodyPart(0).getContent();
        Multipart multipart2 = (Multipart) multipart1.getBodyPart(0).getContent();
        String escapedText = (String) multipart2.getBodyPart(0).getContent();
        String text = StringEscapeUtils.unescapeHtml(escapedText);
        Matcher matcher = Pattern.compile("(http://.*/activate/.*)[\\s]").matcher(text);
        if (matcher.find()) {
            link = matcher.group(1);
        }
    } catch (MessagingException | IOException e) {
        LOGGER.warn("Problem occurred while grabbing activation link from Mailtrap", e);
    }
    return link;
}

From source file:org.socraticgrid.taskmanager.MailHandler.java

private boolean sendMail(String host, String fromUser, boolean isFromUserProvider, String toUser,
        boolean isToUserProvider, String subject, String text) {
    boolean retVal = true;

    try {//from ww w  .ja  va  2 s.  c  o  m
        String fromAddr = getEmailAddr(isFromUserProvider, fromUser);
        String toAddr = getEmailAddr(isToUserProvider, toUser);

        //Get session
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        Session session = Session.getInstance(props);

        //Create messages
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(fromAddr));
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddr));
        msg.setSubject(subject);
        msg.setText(text);
        msg.setHeader("X-Mailer", X_MAILER);
        msg.setSentDate(new Date());

        // send the thing off
        Transport.send(msg);

        log.debug("Mail was sent successfully.");
    } catch (Exception e) {
        log.error("Error sending mail.", e);
        retVal = false;
    }

    return retVal;
}

From source file:org.etudes.component.app.jforum.JForumEmailServiceImpl.java

public void init() {
    if (logger.isInfoEnabled()) {
        logger.info("init....");
    }/*ww w .j  a  v a2  s . co  m*/

    /*wait component manager to cofigure*/
    ComponentManager.waitTillConfigured();

    testMode = serverConfigurationService().getBoolean(EMAIL_TESTMODE, false);

    smtp = System.getProperty(SMTP_HOST);
    if (smtp == null) {
        smtp = serverConfigurationService().getString(SMTP_HOST_SAKAI);

        if (smtp == null || smtp.trim().length() == 0) {
            smtp = null;

            if (logger.isWarnEnabled()) {
                logger.warn("smtp value is not set.");
            }
        }
    }

    smtpPort = System.getProperty(SMTP_PORT);
    if (smtpPort == null) {
        smtpPort = serverConfigurationService().getString(SMTP_PORT_SAKAI);

        if (smtpPort == null || smtpPort.trim().length() == 0) {
            smtpPort = null;
            if (logger.isDebugEnabled()) {
                logger.debug("smtpPort value is not set.");
            }
        }
    }

    smtpFrom = System.getProperty(SMTP_FROM);
    if (this.smtpFrom == null) {
        smtpFrom = POSTMASTER + "@" + serverConfigurationService().getServerName();
    }

    Properties props = new Properties();

    // set the port, if specified
    if (smtpPort != null && smtpPort.trim().length() > 0) {
        props.put(SMTP_PORT, smtpPort);
    }

    // set the mail envelope return address
    props.put(SMTP_FROM, smtpFrom);

    if (smtp == null || smtp.trim().length() == 0) {
        if (logger.isWarnEnabled()) {
            logger.warn("smtp not set");
        }
        return;
    }

    // set the server host
    props.put(SMTP_HOST, smtp);

    session = Session.getInstance(props);
}

From source file:org.sakaiproject.tool.assessment.util.SamigoEmailService.java

public String send() {
    List attachmentList = null;/* ww  w .  j  av  a  2s.  c o  m*/
    AttachmentData a = null;
    try {
        Properties props = new Properties();

        // Server
        if (smtpServer == null || smtpServer.equals("")) {
            log.info("samigo.email.smtpServer is not set");
            smtpServer = ServerConfigurationService.getString("smtp@org.sakaiproject.email.api.EmailService");
            if (smtpServer == null || smtpServer.equals("")) {
                log.info("smtp@org.sakaiproject.email.api.EmailService is not set");
                log.error(
                        "Please set the value of samigo.email.smtpServer or smtp@org.sakaiproject.email.api.EmailService");
                return "error";
            }
        }
        props.setProperty("mail.smtp.host", smtpServer);

        // Port
        if (smtpPort == null || smtpPort.equals("")) {
            log.warn("samigo.email.smtpPort is not set. The default port 25 will be used.");
        } else {
            props.setProperty("mail.smtp.port", smtpPort);
        }

        Session session;
        session = Session.getInstance(props);
        session.setDebug(true);
        MimeMessage msg = new MimeMessage(session);

        InternetAddress fromIA = new InternetAddress(fromEmailAddress, fromName);
        msg.setFrom(fromIA);
        InternetAddress[] toIA = { new InternetAddress(toEmailAddress, toName) };
        msg.setRecipients(Message.RecipientType.TO, toIA);

        if ("yes".equals(ccMe)) {
            InternetAddress[] ccIA = { new InternetAddress(fromEmailAddress, fromName) };
            msg.setRecipients(Message.RecipientType.CC, ccIA);
        }
        msg.setSubject(subject);

        EmailBean emailBean = (EmailBean) ContextUtil.lookupBean("email");
        attachmentList = emailBean.getAttachmentList();
        StringBuilder content = new StringBuilder(message);
        ArrayList fileList = new ArrayList();
        ArrayList fileNameList = new ArrayList();
        if (attachmentList != null) {
            if (prefixedPath == null || prefixedPath.equals("")) {
                log.error("samigo.email.prefixedPath is not set");
                return "error";
            }
            Iterator iter = attachmentList.iterator();
            while (iter.hasNext()) {
                a = (AttachmentData) iter.next();
                if (a.getIsLink().booleanValue()) {
                    log.debug("send(): url");
                    content.append("<br/>\n\r");
                    content.append("<br/>"); // give a new line
                    content.append(a.getFilename());
                } else {
                    log.debug("send(): file");
                    File attachedFile = getAttachedFile(a.getResourceId());
                    fileList.add(attachedFile);
                    fileNameList.add(a.getFilename());
                }
            }
        }

        Multipart multipart = new MimeMultipart();
        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(content.toString(), "text/html");
        multipart.addBodyPart(messageBodyPart);
        msg.setContent(multipart);

        for (int i = 0; i < fileList.size(); i++) {
            messageBodyPart = new MimeBodyPart();
            FileDataSource source = new FileDataSource((File) fileList.get(i));
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName((String) fileNameList.get(i));
            multipart.addBodyPart(messageBodyPart);
        }
        msg.setContent(multipart);

        Transport.send(msg);
    } catch (UnsupportedEncodingException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (MessagingException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (ServerOverloadException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (PermissionException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (IdUnusedException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (TypeException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (IOException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } finally {
        if (attachmentList != null) {
            if (prefixedPath != null && !prefixedPath.equals("")) {
                StringBuilder sbPrefixedPath;
                Iterator iter = attachmentList.iterator();
                while (iter.hasNext()) {
                    sbPrefixedPath = new StringBuilder(prefixedPath);
                    sbPrefixedPath.append("/email_tmp/");
                    a = (AttachmentData) iter.next();
                    if (!a.getIsLink().booleanValue()) {
                        deleteAttachedFile(sbPrefixedPath.append(a.getResourceId()).toString());
                    }
                }
            }
        }
    }
    return "send";
}

From source file:ste.xtest.mail.BugFreeFileTransport.java

@Test
public void send_multipart_message() throws Exception {
    Session session = Session.getInstance(config);

    Message message = new MimeMessage(Session.getInstance(config));
    message.setFrom(new InternetAddress("from@domain.com"));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress("to@domain.com"));
    message.setSubject("the subject");
    MimeMultipart multipart = new MimeMultipart("related");

    BodyPart messageBodyPart = new MimeBodyPart();
    String htmlText = "<H1>hello world</H1><img src=\"cid:image\">";
    messageBodyPart.setContent(htmlText, "text/html");
    multipart.addBodyPart(messageBodyPart);
    messageBodyPart = new MimeBodyPart();
    DataSource fds = new FileDataSource("src/test/resources/images/6096.png");

    messageBodyPart.setDataHandler(new DataHandler(fds));
    messageBodyPart.setHeader("Content-ID", "<image>");

    multipart.addBodyPart(messageBodyPart);
    message.setContent(multipart);/*from   w w w.  j av a  2 s. c  o m*/

    session.getTransport().sendMessage(message, message.getAllRecipients());

    then(FileUtils.readFileToString(new File(TMP.getRoot(), "message"))).contains("From: from@domain.com\r")
            .contains("To: to@domain.com\r").contains("Subject: the subject\r").contains("hello world")
            .contains("Content-ID: <image>");
}

From source file:atd.backend.Register.java

public void sendRegMail(Klant k) throws IOException {
    Properties propMail = new Properties();
    InputStream config = null;//from   w  ww .j a v a 2s .c o m
    config = new URL(CONFIG_URL).openStream();
    propMail.load(config);

    Properties props = new Properties();
    props.put("mail.smtp.host", propMail.getProperty("host"));
    props.put("mail.smtp.port", 465);
    props.put("mail.smtp.ssl.enable", true);
    Session mailSession = Session.getInstance(props);
    try {
        Logger.getLogger("atd.log").info("Stuurt mail naar: " + k.getEmail());
        MimeMessage msg = new MimeMessage(mailSession);
        msg.setFrom(new InternetAddress(propMail.getProperty("email"), propMail.getProperty("mailName")));
        msg.setRecipients(Message.RecipientType.TO, k.getEmail());
        msg.setSubject("Uw account is aangemaakt");
        msg.setSentDate(Calendar.getInstance().getTime());
        msg.setContent("Beste " + k.getNaam() + ", \n\nUw account " + k.getUsername()
                + " is aangemaakt, U kunt inloggen op de <a href='https://atd.plebian.nl'>ATD website</a>\n",
                "text/html; charset=utf-8");
        // TODO: Heeft OAUTH nodig, maarja we zijn al niet erg netjes met
        // wachtwoorden
        Transport.send(msg, propMail.getProperty("email"), propMail.getProperty("password"));
    } catch (Exception e) {
        Logger.getLogger("atd.log").warning("send failed: " + e.getMessage());
    }
}

From source file:gov.nih.nci.firebird.service.messages.email.EmailServiceImplTest.java

@Before
public void setUp() throws AddressException {
    props = new Properties();
    props.setProperty(Email.MAIL_PORT, "25");
    session = Session.getInstance(props);
    mailbox = Mailbox.get(TEST_TO_ADDRESS);
    bean = new EmailServiceImpl();
    bean.setSenderName(TEST_FROM_NAME);//from  w  ww  .  ja va  2  s. co m
    bean.setSenderEmail(TEST_FROM_ADDRESS);
    bean.setMailSession(session);
    bean.setSendMail(true);
}

From source file:com.evolveum.midpoint.notifications.impl.api.transports.MailTransport.java

@Override
public void send(Message mailMessage, String transportName, 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 = NotificationsUtil
            .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);//from w ww  . j av a  2s .co  m
        result.recordWarning(msg);
        return;
    }

    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 from = 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;
        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);
            mimeMessage.setFrom(new InternetAddress(from));
            for (String recipient : mailMessage.getTo()) {
                mimeMessage.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(recipient));
            }
            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);
}