Example usage for javax.mail Session getDefaultInstance

List of usage examples for javax.mail Session getDefaultInstance

Introduction

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

Prototype

public static Session getDefaultInstance(Properties props) 

Source Link

Document

Get the default Session object.

Usage

From source file:EmailBean.java

public void sendMessage() throws Exception {

    Properties properties = System.getProperties();

    //populate the 'Properties' object with the mail
    //server address, so that the default 'Session'
    //instance can use it.
    properties.put("mail.smtp.host", smtpHost);

    Session session = Session.getDefaultInstance(properties);

    Message mailMsg = new MimeMessage(session);//a new email message

    InternetAddress[] addresses = null;//from  www.j a  va2  s . c  o m

    try {

        if (to != null) {

            //throws 'AddressException' if the 'to' email address
            //violates RFC822 syntax
            addresses = InternetAddress.parse(to, false);

            mailMsg.setRecipients(Message.RecipientType.TO, addresses);

        } else {

            throw new MessagingException("The mail message requires a 'To' address.");

        }

        if (from != null) {

            mailMsg.setFrom(new InternetAddress(from));

        } else {

            throw new MessagingException("The mail message requires a valid 'From' address.");

        }

        if (subject != null)
            mailMsg.setSubject(subject);

        if (content != null)
            mailMsg.setText(content);

        //Finally, send the mail message; throws a 'SendFailedException'
        //if any of the message's recipients have an invalid address
        Transport.send(mailMsg);

    } catch (Exception exc) {

        throw exc;

    }

}

From source file:ch.unibas.fittingwizard.application.tools.Notifications.java

private void sendMailTesting() {
    try {// w  w  w  .j  a v a 2  s . c  o m
        Email email = new SimpleEmail();
        email.setMailSession(Session.getDefaultInstance(props));

        email.setSubject("Test mail");
        email.setMsg("This is a test mail for checking parameters from config file");
        email.setFrom(getSender().trim());
        email.addTo(getRecipient().trim());

        email.send();
    } catch (EmailException e) {
        throw new RuntimeException("Could not send notification.", e);
    }
}

From source file:se.vgregion.mobile.services.SmtpErrorReportService.java

@Override
public void report(ErrorReport report) {
    Properties props = new Properties();
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);

    Session mailSession = Session.getDefaultInstance(props);
    Message simpleMessage = new MimeMessage(mailSession);

    try {/*from w w  w  .ja va  2 s.c  o  m*/
        InternetAddress fromAddress = new InternetAddress(from);
        InternetAddress toAddress = new InternetAddress(to);

        simpleMessage.setFrom(fromAddress);
        simpleMessage.setRecipient(RecipientType.TO, toAddress);
        simpleMessage.setSubject(subject);

        String text = String.format(body, report.getPrinter().getName(), report.getDescription(),
                report.getReporter());
        simpleMessage.setText(text);

        Transport.send(simpleMessage);
    } catch (MessagingException e) {
        throw new RuntimeException("Failed sending error report via mail", e);
    }

}

From source file:mail.MailService.java

/**
 * Erstellt eine MIME-Mail./*from  w  ww. ja v a  2 s  . c o  m*/
 * @param email
 * @throws MessagingException
 * @throws IOException
 */
public String createMail1(Mail email, Config config) throws MessagingException, IOException {

    Properties props = new Properties();
    props.put("mail.smtp.host", "mail.java-tutor.com");
    Session session = Session.getDefaultInstance(props);

    Message msg = new MimeMessage(session);
    //      msg.setHeader("MIME-Version" , "1.0"); 
    //      msg.setHeader("Content-Type" , "text/plain"); 

    // Absender
    InternetAddress addressFrom = new InternetAddress(email.getAbsender());
    msg.setFrom(addressFrom);

    // Empfnger
    InternetAddress addressTo = new InternetAddress(email.getEmpfaenger());
    msg.setRecipient(Message.RecipientType.TO, addressTo);

    msg.setSubject(email.getBetreff());
    msg.setSentDate(email.getAbsendeDatum());
    String txt = Utils.toString(email.getText());

    msg.setText(txt);
    msg.saveChanges();

    // Mail in Ausgabestrom schreiben
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    try {
        msg.writeTo(bOut);
    } catch (IOException e) {
        if (config.isTest())
            System.out.println("Fehler beim Schreiben der Mail in Schritt 1");
        throw e;
    }
    return removeMessageId(bOut.toString(Charset.defaultCharset().name()));
}

From source file:org.apache.james.jmap.utils.MimeMessageBodyGeneratorTest.java

@Before
public void setUp() {
    original = new MimeMessage(Session.getDefaultInstance(new Properties()));
    htmlTextExtractor = mock(HtmlTextExtractor.class);
    mimeMessageBodyGenerator = new MimeMessageBodyGenerator(htmlTextExtractor);
}

From source file:com.intuit.tank.mail.TankMailer.java

/**
 * @{inheritDoc//from ww w.  j a va 2 s. c  o  m
 */
@Override
public void sendMail(MailMessage message, String... emailAddresses) {
    MailConfig mailConfig = new TankConfig().getMailConfig();
    Properties props = new Properties();
    props.put("mail.smtp.host", mailConfig.getSmtpHost());
    props.put("mail.smtp.port", mailConfig.getSmtpPort());

    Session mailSession = Session.getDefaultInstance(props);
    Message simpleMessage = new MimeMessage(mailSession);

    InternetAddress fromAddress = null;
    InternetAddress toAddress = null;
    try {
        fromAddress = new InternetAddress(mailConfig.getMailFrom());
        simpleMessage.setFrom(fromAddress);
        for (String email : emailAddresses) {
            try {
                toAddress = new InternetAddress(email);
                simpleMessage.addRecipient(RecipientType.TO, toAddress);
            } catch (AddressException e) {
                LOG.warn("Error with recipient " + email + ": " + e.toString());
            }
        }

        simpleMessage.setSubject(message.getSubject());
        final MimeBodyPart textPart = new MimeBodyPart();
        textPart.setContent(message.getPlainTextBody(), "text/plain");
        textPart.setHeader("MIME-Version", "1.0");
        textPart.setHeader("Content-Type", textPart.getContentType());
        // HTML version
        final MimeBodyPart htmlPart = new MimeBodyPart();
        // htmlPart.setContent(message.getHtmlBody(), "text/html");
        htmlPart.setDataHandler(new DataHandler(new HTMLDataSource(message.getHtmlBody())));
        htmlPart.setHeader("MIME-Version", "1.0");
        htmlPart.setHeader("Content-Type", "text/html");
        // Create the Multipart. Add BodyParts to it.
        final Multipart mp = new MimeMultipart("alternative");
        mp.addBodyPart(textPart);
        mp.addBodyPart(htmlPart);
        // Set Multipart as the message's content
        simpleMessage.setContent(mp);
        simpleMessage.setHeader("MIME-Version", "1.0");
        simpleMessage.setHeader("Content-Type", mp.getContentType());
        logMsg(mailConfig.getSmtpHost(), simpleMessage);
        if (simpleMessage.getRecipients(RecipientType.TO) != null
                && simpleMessage.getRecipients(RecipientType.TO).length > 0) {
            Transport.send(simpleMessage);
        }
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:edu.wright.cs.fa15.ceg3120.concon.server.EmailManager.java

/**
 * Add an outgoing email to the queue./*from ww w  .  j  av  a  2 s .co  m*/
 * @param to Array of email addresses.
 * @param subject Header
 * @param body Content
 * @param attachmentFile Attachment
 */
public void addEmail(String[] to, String subject, String body, File attachmentFile) {
    HtmlEmail mail = new HtmlEmail();
    Properties sysProps = System.getProperties();

    // Setup mail server
    sysProps.setProperty("mail.smtp.host", props.getProperty("mail_server_hostname"));
    Session session = Session.getDefaultInstance(sysProps);

    try {
        mail.setMailSession(session);
        mail.setFrom(props.getProperty("server_email_addr"), props.getProperty("server_title"));
        mail.addTo(to);
        mail.setSubject(subject);
        mail.setTextMsg(body);
        mail.setHtmlMsg(composeAsHtml(mail, body));
        if (attachmentFile.exists()) {
            EmailAttachment attachment = new EmailAttachment();
            attachment.setPath(attachmentFile.getPath());
            mail.attach(attachment);
        }
    } catch (EmailException e) {
        LOG.warn("Email was not added. ", e);
    }
    mailQueue.add(mail);
}

From source file:au.org.ala.biocache.service.EmailService.java

/**
 * Sends an email with the supplied details. 
 * /*  w ww. ja  va 2  s  .c o m*/
 * @param recipient
 * @param subject
 * @param content
 * @param sender
 */
public void sendEmail(String recipient, String subject, String content, String sender) {

    logger.debug("Send email to : " + recipient);
    logger.debug("Body: " + content);
    Session session = Session.getDefaultInstance(properties);

    try {

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(sender));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
        message.setSubject(subject);
        message.setContent(content, "text/html");
        Transport.send(message);
    } catch (Exception e) {
        logger.error("Unable to send email to " + recipient + ".\n" + content, e);
    }
}

From source file:org.mot.common.tools.EmailFactory.java

public EmailFactory() {

    Configuration emailProps;/*from ww w  . j ava  2  s  .co  m*/
    try {
        emailProps = new PropertiesConfiguration(pf.getConfigDir() + "/email.properties");

        enabled = emailProps.getBoolean("email.enabled", true);
        from = emailProps.getString("email.sender", "info@myopentrader.org");
        rcpt = emailProps.getString("email.recipient", "stephan@myopentrader.org");
        host = emailProps.getString("email.smtp.host", "localhost");

        // Get system properties
        Properties properties = System.getProperties();

        // Setup mail server
        properties.setProperty("mail.smtp.host", host);

        session = Session.getDefaultInstance(properties);

    } catch (ConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.overlord.sramp.governance.services.NotificationResourceTest.java

@Test
public void testMail() {
    try {/*from   w w  w.j av  a 2 s  . co  m*/
        mailServer = SimpleSmtpServer.start(smtpPort);
        Properties properties = new Properties();
        properties.setProperty("mail.smtp.host", "localhost"); //$NON-NLS-1$ //$NON-NLS-2$
        properties.setProperty("mail.smtp.port", String.valueOf(smtpPort)); //$NON-NLS-1$
        Session mailSession = Session.getDefaultInstance(properties);
        MimeMessage m = new MimeMessage(mailSession);
        Address from = new InternetAddress("me@gmail.com"); //$NON-NLS-1$
        Address[] to = new InternetAddress[1];
        to[0] = new InternetAddress("dev@mailinator.com"); //$NON-NLS-1$
        m.setFrom(from);
        m.setRecipients(Message.RecipientType.TO, to);
        m.setSubject("test"); //$NON-NLS-1$
        m.setContent("test", "text/plain"); //$NON-NLS-1$ //$NON-NLS-2$
        Transport.send(m);

        Assert.assertTrue(mailServer.getReceivedEmailSize() > 0);
        @SuppressWarnings("rawtypes")
        Iterator iter = mailServer.getReceivedEmail();
        while (iter.hasNext()) {
            SmtpMessage email = (SmtpMessage) iter.next();
            System.out.println(email.getBody());
            Assert.assertEquals("test", email.getBody()); //$NON-NLS-1$
        }

    } catch (AddressException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        mailServer.stop();
    }

}