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, Authenticator authenticator) 

Source Link

Document

Get a new Session object.

Usage

From source file:quickforms.sme.UseFulMethods.java

static public void sendEmail(String d_email, String pwd, String m_to, String m_subject, String message)
        throws Exception {
    final String from = d_email;
    final String password = pwd;
    class SMTPAuthenticator extends Authenticator {

        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(from, password);
        }//from w w w.jav  a 2  s.c  o  m
    }

    //String d_uname = "email";
    //String d_password = "password";
    String d_host = "smtp.gmail.com";
    String d_port = "465"; //465,587

    Properties props = new Properties();
    props.put("mail.smtp.user", from);
    props.put("mail.smtp.host", d_host);
    props.put("mail.smtp.port", d_port);
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.debug", "true");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.socketFactory.port", d_port);
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");

    SMTPAuthenticator auth = new SMTPAuthenticator();
    Session session = Session.getInstance(props, auth);
    session.setDebug(true);

    MimeMessage msg = new MimeMessage(session);

    //msg.setText(message);
    // Send the actual HTML message, as big as you like

    msg.setContent(message, "text/html");
    msg.setSubject(m_subject);
    msg.setFrom(new InternetAddress(from));
    msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));

    Transport transport = session.getTransport("smtps");
    transport.connect(d_host, 465, from, password);
    transport.sendMessage(msg, msg.getAllRecipients());
    transport.close();

}

From source file:org.opennms.javamail.JavaReadMailer.java

/**
 * <p>Constructor for JavaReadMailer.</p>
 *
 * @param config a {@link org.opennms.netmgt.config.javamail.ReadmailConfig} object.
 * @param closeOnDelete a {@link java.lang.Boolean} object.
 * @throws org.opennms.javamail.JavaMailerException if any.
 *///from  ww  w.  j a va2s.c o  m
public JavaReadMailer(final ReadmailConfig config, Boolean closeOnDelete) throws JavaMailerException {
    if (closeOnDelete != null) {
        m_deleteOnClose = closeOnDelete;
    }
    m_config = config;
    m_session = Session.getInstance(configureProperties(),
            createAuthenticator(config.getUserAuth().getUserName(), config.getUserAuth().getPassword()));
}

From source file:org.eclipse.skalli.core.mail.MailComponent.java

private void sendMailInternal(Address[] rcptTo, Address[] rcptCC, Address[] rcptBCC, Address from,
        String subject, String body) {
    try {/* w  ww.  j a  v  a  2 s .  c  om*/
        String mailHost = "mail.sap.corp"; //$NON-NLS-1$
        Properties props = System.getProperties();
        props.put("mail.smtp.host", mailHost); //$NON-NLS-1$
        Session session = Session.getInstance(props, null);
        Message message = new MimeMessage(session);
        message.setFrom(from);
        if (rcptTo != null && rcptTo.length > 0) {
            message.setRecipients(Message.RecipientType.TO, rcptTo);
        }
        if (rcptCC != null && rcptCC.length > 0) {
            message.setRecipients(Message.RecipientType.CC, rcptCC);
        }
        if (rcptBCC != null && rcptBCC.length > 0) {
            message.setRecipients(Message.RecipientType.BCC, rcptBCC);
        }

        message.setSubject(subject);
        message.setContent(body, "text/plain"); //$NON-NLS-1$
        Transport.send(message);
    } catch (AddressException e) {
        throw new RuntimeException(e);
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.hs.mail.mailet.RemoteDelivery.java

/**
 * Initialize the mailet/*from  w  w  w .  j a v  a2s.co  m*/
 */
public void init(MailetContext context) {
    super.init(context);
    Properties props = new Properties();
    Properties sysprops = System.getProperties();
    for (Object key : sysprops.keySet()) {
        if (((String) key).startsWith("mail.")) {
            props.put(key, sysprops.get(key));
        }
    }
    if (this.debug)
        props.setProperty("mail.debug", "true");
    props.setProperty("mail.smtp.timeout", smtpTimeout + "");
    props.setProperty("mail.smtp.connectiontimeout", connectionTimeout + "");
    props.setProperty("mail.smtp.sendpartial", String.valueOf(sendPartial));
    props.setProperty("mail.smtp.localhost", Config.getHelloName());

    this.maxRetries = (int) Config.getNumberProperty("max_retry_count", 3);

    this.session = Session.getInstance(props, null);
    this.session.setDebug(this.debug);

    this.gateway = Config.getProperty("smtp_gateway", null);
    this.authUser = Config.getProperty("smtp_gateway_username", null);
    this.authPass = Config.getProperty("smtp_gateway_password", null);
}

From source file:net.wastl.webmail.plugins.SendMessage.java

protected void init() {
    Properties props = new Properties();
    props.put("mail.host", store.getConfig("SMTP HOST"));
    props.put("mail.smtp.host", store.getConfig("SMTP HOST"));
    mailsession = Session.getInstance(props, null);
}

From source file:org.springframework.mail.javamail.JavaMailSenderImpl.java

/**
 * Set JavaMail properties for the <code>Session</code>.
 * <p>A new <code>Session</code> will be created with those properties.
 * Use either this method or {@link #setSession}, but not both.
 * <p>Non-default properties in this instance will override given
 * JavaMail properties./*from   ww w  . j a v  a2  s  .co  m*/
 */
public void setJavaMailProperties(Properties javaMailProperties) {
    this.session = Session.getInstance(javaMailProperties, null);
}

From source file:org.apache.synapse.transport.mail.MailEchoRawXMLTest.java

public void testRoundTripPOX() throws Exception {

    String msgId = UUIDGenerator.getUUID();

    Session session = Session.getInstance(props, new Authenticator() {
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("synapse.test.1", "mailpassword");
        }/* w ww .  j  a  va 2s .co  m*/
    });
    session.setDebug(log.isTraceEnabled());

    WSMimeMessage msg = new WSMimeMessage(session);
    msg.setFrom(new InternetAddress("synapse.test.0@gmail.com"));
    msg.setReplyTo(InternetAddress.parse("synapse.test.0@gmail.com"));
    InternetAddress[] address = { new InternetAddress("synapse.test.6@gmail.com") };
    msg.setRecipients(Message.RecipientType.TO, address);
    msg.setSubject("POX Roundtrip");
    msg.setHeader(BaseConstants.SOAPACTION, Constants.AXIS2_NAMESPACE_URI + "/echoOMElement");
    msg.setSentDate(new Date());
    msg.setHeader(MailConstants.MAIL_HEADER_MESSAGE_ID, msgId);
    msg.setHeader(MailConstants.MAIL_HEADER_X_MESSAGE_ID, msgId);
    msg.setText(POX_MESSAGE);
    Transport.send(msg);

    Thread.yield();
    Thread.sleep(1000 * 10);

    Object reply = null;
    boolean replyNotFound = true;
    int retryCount = 3;
    while (replyNotFound) {
        log.debug("Checking for response ... with MessageID : " + msgId);
        reply = getMessage(msgId);
        if (reply != null) {
            replyNotFound = false;
        } else {
            if (retryCount-- > 0) {
                Thread.sleep(10000);
            } else {
                break;
            }
        }
    }

    if (reply != null && reply instanceof String) {
        log.debug("Result Body : " + reply);
        XMLStreamReader reader = StAXUtils.createXMLStreamReader(new StringReader((String) reply));
        OMElement res = new StAXOMBuilder(reader).getDocumentElement();
        if (res != null) {
            AXIOMXPath xpath = new AXIOMXPath("//my:myValue");
            xpath.addNamespace("my", "http://localhost/axis2/services/EchoXMLService");
            Object result = xpath.evaluate(res);
            if (result != null && result instanceof OMElement) {
                assertEquals("omTextValue", ((OMElement) result).getText());
            }
        }
    } else {
        fail("Did not receive the reply mail");
    }
}

From source file:org.codice.ddf.platform.email.impl.SmtpClientImpl.java

@Override
public Session createSession() {

    Properties properties = new Properties();

    if (hostName == null) {
        throw new IllegalArgumentException("Hostname cannot be null for smtp client.");
    }//from   w w w  .  j a v a 2  s . c  o  m

    properties.setProperty(SMTP_HOST_PROPERTY, hostName);
    properties.setProperty(SMTP_PORT_PROPERTY, portNumber.toString());

    if (StringUtils.isNotBlank(userName)) {
        properties.put(SMTP_AUTH_PROPERTY, TRUE);
        properties.put(SMTP_START_TLS_ENABLE_PROPERTY, TRUE);

        return Session.getInstance(properties, createAuthenticator());
    } else {
        properties.setProperty(SMTP_AUTH_PROPERTY, FALSE);
        return Session.getInstance(properties);
    }
}

From source file:be.fedict.eid.dss.model.bean.TaskMDB.java

private void sendMail(String mailTo, String subject, String messageBody, String attachmentMimetype,
        byte[] attachment) {
    LOG.debug("sending email to " + mailTo + " with subject \"" + subject + "\"");
    String smtpServer = this.configuration.getValue(ConfigProperty.SMTP_SERVER, String.class);
    if (null == smtpServer || smtpServer.trim().isEmpty()) {
        LOG.warn("no SMTP server configured");
        return;//from   ww w. j  a v a 2  s  . c  o m
    }
    String mailFrom = this.configuration.getValue(ConfigProperty.MAIL_FROM, String.class);
    if (null == mailFrom || mailFrom.trim().isEmpty()) {
        LOG.warn("no mail from address configured");
        return;
    }
    LOG.debug("mail from: " + mailFrom);

    Properties props = new Properties();
    props.put("mail.smtp.host", smtpServer);
    props.put("mail.from", mailFrom);

    String mailPrefix = this.configuration.getValue(ConfigProperty.MAIL_PREFIX, String.class);
    if (null != mailPrefix && false == mailPrefix.trim().isEmpty()) {
        subject = "[" + mailPrefix.trim() + "] " + subject;
    }

    Session session = Session.getInstance(props, null);
    try {
        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setFrom();
        mimeMessage.setRecipients(RecipientType.TO, mailTo);
        mimeMessage.setSubject(subject);
        mimeMessage.setSentDate(new Date());

        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        mimeBodyPart.setText(messageBody);

        Multipart multipart = new MimeMultipart();
        // first part is body
        multipart.addBodyPart(mimeBodyPart);

        // second part is attachment
        if (null != attachment) {
            MimeBodyPart attachmentMimeBodyPart = new MimeBodyPart();
            DataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimetype);
            attachmentMimeBodyPart.setDataHandler(new DataHandler(dataSource));
            multipart.addBodyPart(attachmentMimeBodyPart);
        }

        mimeMessage.setContent(multipart);
        Transport.send(mimeMessage);
    } catch (MessagingException e) {
        throw new RuntimeException("send failed, exception: " + e.getMessage(), e);
    }
}

From source file:org.eurekastreams.server.service.actions.strategies.EmailerFactory.java

/**
 * Creates a "blank" email message, ready for the application to set the content (subject, body, etc.).
 *
 * @return An email message./*from w  w  w  . j a v a  2 s.  c  o m*/
 * @throws MessagingException
 *             Thrown if there are problems creating the message.
 */
public MimeMessage createMessage() throws MessagingException {
    Properties mailProps = new Properties();
    mailProps.put("mail.transport.protocol", mailTransportProtocol);
    for (Map.Entry<String, String> cfg : transportConfiguration.entrySet()) {
        mailProps.put(cfg.getKey(), cfg.getValue());
    }
    Session mailSession = Session.getInstance(mailProps, null);

    MimeMessage msg = new MimeMessage(mailSession);
    msg.setContent(new MimeMultipart("alternative"));
    msg.setSentDate(new Date());
    msg.setFrom(new InternetAddress(defaultFromAddress));

    return msg;
}