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:org.alfresco.repo.imap.IncomingImapMessage.java

/**
 * Constructs {@link IncomingImapMessage} object based on {@link MimeMessage}
 * /*from  w  w  w  . j  a v a2  s . c o m*/
 * @param fileInfo - reference to the {@link FileInfo} object representing the message.
 * @param serviceRegistry - reference to serviceRegistry object.
 * @param message - {@link MimeMessage}
 * @throws MessagingException
 */
public IncomingImapMessage(FileInfo fileInfo, ServiceRegistry serviceRegistry, MimeMessage message)
        throws MessagingException {
    super(Session.getDefaultInstance(new Properties()));
    this.wrappedMessage = message; // temporary save it and then destroyed in writeContent() (to avoid memory leak with byte[] MimeMessage.content field)
    this.buildMessage(fileInfo, serviceRegistry);
}

From source file:org.tsm.concharto.service.EmailService.java

/**
 *
 * @param subject//from  w w w  . ja  va 2s  .c  o m
 * @param body
 * @param sender
 * @param recipients
 */
public void SendIndividualMessages(String subject, String body, InternetAddress sender, String[] recipients) {
    int emailErrorCount = 0;
    for (int i = 0; i < recipients.length; i++) {
        String recipientEmailAddress = recipients[i];
        MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));
        try {
            message.setText(body);
            message.setSubject(subject);
            message.setFrom(sender);
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipientEmailAddress));
            sendMessage(message);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            emailErrorCount++;
        }
    }
    if (emailErrorCount > 0) {
        String message = emailErrorCount + " out of " + recipients.length + " emails could not be sent.";
        log.error(message);
    }
}

From source file:org.tizzit.util.mail.Mail.java

/**
 * For testing purposes: Value constructor that creates a mail and its session based
 * on the specified properties./*  w  w  w .  java2 s  .  c o  m*/
 * 
 * @param testProperties {@link Properties} containing at least a valid entry for "mail.host"
 */
public Mail(Properties testProperties) {
    Session session = Session.getDefaultInstance(testProperties);
    if (session == null) {
        throw new IllegalArgumentException("session could not be initialized with specified properties");
    }
    initializeMail(session);
}

From source file:com.srotya.tau.nucleus.qa.QAAlertRules.java

@Test
public void testASMTPServerAvailability() throws UnknownHostException, IOException, MessagingException {
    MimeMessage msg = new MimeMessage(Session.getDefaultInstance(new Properties()));
    msg.setFrom(new InternetAddress("alert@srotya.com"));
    msg.setRecipient(RecipientType.TO, new InternetAddress("alert@srotya.com"));
    msg.setSubject("test mail");
    msg.setContent("Hello", "text/html");
    Transport.send(msg);//from   ww w .  j a v a  2s . c  o m
    MailService ms = new MailService();
    ms.init(new HashMap<>());
    Alert alert = new Alert();
    alert.setBody("test");
    alert.setId((short) 0);
    alert.setMedia("test");
    alert.setSubject("test");
    alert.setTarget("alert@srotya.com");
    ms.sendMail(alert);
    assertEquals(2, AllQATests.getSmtpServer().getReceivedEmailSize());
    System.err.println("Mail sent");
}

From source file:com.trivago.mail.pigeon.mail.MailFacade.java

public void readBounceAccount() throws MessagingException {
    Session session = Session.getDefaultInstance(Settings.create().getConfiguration().getProperties("mail.*"));
    Store store = session.getStore("pop3");

    store.connect();/*from   ww w .j  a  v  a 2s  .  c  om*/

    // Get folder
    Folder folder = store.getFolder("INBOX");
    folder.open(Folder.READ_ONLY);

    if (folder.hasNewMessages()) {
        // Get directory
        Message message[] = folder.getMessages();
        BounceFacade bounceFacade = new BounceFacade();

        for (Message msg : message) {
            boolean isBounce = bounceFacade.processBounce(msg);
            if (isBounce) {
                msg.setFlag(Flags.Flag.SEEN, true);
                msg.saveChanges();
            }
        }
    }

}

From source file:dk.netarkivet.common.utils.EMailUtils.java

/**
 * Send an email, possibly forgiving errors.
 *
 * @param to The recipient of the email. Separate multiple recipients with
 *           commas. Supports only adresses of the type 'john@doe.dk', not
 *           'John Doe <john@doe.dk>'
 * @param from The sender of the email.//from   w  w  w  . j  a  v a 2 s  .  c o m
 * @param subject The subject of the email.
 * @param body The body of the email.
 * @param forgive On true, will send the email even on invalid email
 *        addresses, if at least one recipient can be set, on false, will
 *        throw exceptions on any invalid email address.
 *
 *
 * @throws ArgumentNotValid If either parameter is null, if to, from or
 *                          subject is the empty string, or no recipient
 *                          can be set. If "forgive" is false, also on
 *                          any invalid to or from address.
 * @throws IOFailure If the message cannot be sent for some reason.
 */
public static void sendEmail(String to, String from, String subject, String body, boolean forgive) {
    ArgumentNotValid.checkNotNullOrEmpty(to, "String to");
    ArgumentNotValid.checkNotNullOrEmpty(from, "String from");
    ArgumentNotValid.checkNotNullOrEmpty(subject, "String subject");
    ArgumentNotValid.checkNotNull(body, "String body");

    Properties props = new Properties();
    props.put(MAIL_FROM_PROPERTY_KEY, from);
    props.put(MAIL_HOST_PROPERTY_KEY, Settings.get(CommonSettings.MAIL_SERVER));

    Session session = Session.getDefaultInstance(props);
    Message msg = new MimeMessage(session);

    // to might contain more than one e-mail address
    for (String toAddressS : to.split(",")) {
        try {
            InternetAddress toAddress = new InternetAddress(toAddressS.trim());
            msg.addRecipient(Message.RecipientType.TO, toAddress);
        } catch (AddressException e) {
            if (forgive) {
                log.warn("To address '" + toAddressS + "' is not a valid email " + "address", e);
            } else {
                throw new ArgumentNotValid("To address '" + toAddressS + "' is not a valid email " + "address",
                        e);
            }
        } catch (MessagingException e) {
            if (forgive) {
                log.warn("To address '" + toAddressS + "' could not be set in email", e);
            } else {
                throw new ArgumentNotValid("To address '" + toAddressS + "' could not be set in email", e);
            }
        }
    }
    try {
        if (msg.getAllRecipients().length == 0) {
            throw new ArgumentNotValid("No valid recipients in '" + to + "'");
        }
    } catch (MessagingException e) {
        throw new ArgumentNotValid("Message invalid after setting" + " recipients", e);
    }

    try {
        InternetAddress fromAddress = null;
        fromAddress = new InternetAddress(from);
        msg.setFrom(fromAddress);
    } catch (AddressException e) {
        throw new ArgumentNotValid("From address '" + from + "' is not a valid email " + "address", e);
    } catch (MessagingException e) {
        if (forgive) {
            log.warn("From address '" + from + "' could not be set in email", e);
        } else {
            throw new ArgumentNotValid("From address '" + from + "' could not be set in email", e);
        }
    }

    try {
        msg.setSubject(subject);
        msg.setContent(body, MIMETYPE);
        msg.setSentDate(new Date());
        Transport.send(msg);
    } catch (MessagingException e) {
        throw new IOFailure("Could not send email with subject '" + subject + "' from '" + from + "' to '" + to
                + "'. Body:\n" + body, e);
    }
}

From source file:com.threewks.thundr.mail.JavaMailMailer.java

protected Session getSession() {
    return Session.getDefaultInstance(new Properties());
}

From source file:com.rest.it.TestData.java

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
    when(mailSender.createMimeMessage())
            .thenReturn(new MimeMessage(Session.getDefaultInstance(new Properties())));
}

From source file:EmailBean.java

private void handleMessages(HttpServletRequest request, PrintWriter out) throws IOException, ServletException {

    HttpSession httpSession = request.getSession();
    String user = (String) httpSession.getAttribute("user");
    String password = (String) httpSession.getAttribute("pass");
    String popAddr = (String) httpSession.getAttribute("pop");

    Store popStore = null;/* www .ja  v a  2s .  c o  m*/
    Folder folder = null;

    if (!check(popAddr))
        popAddr = EmailBean.DEFAULT_SERVER;

    try {

        if ((!check(user)) || (!check(password)))
            throw new ServletException("A valid username and password is required to check email.");

        Properties properties = System.getProperties();

        Session session = Session.getDefaultInstance(properties);

        popStore = session.getStore("pop3");

        popStore.connect(popAddr, user, password);

        folder = popStore.getFolder("INBOX");

        if (!folder.exists())
            throw new ServletException("An 'INBOX' folder does not exist for the user.");

        folder.open(Folder.READ_ONLY);

        Message[] messages = folder.getMessages();
        int msgLen = messages.length;

        if (msgLen == 0)
            out.println("<h2>The INBOX folder does not yet contain any email messages.</h2>");

        for (int i = 0; i < msgLen; i++) {
            displayMessage(messages[i], out);
            out.println("<br /><br />");
        }

    } catch (Exception exc) {

        out.println("<h2>Sorry, an error occurred while accessing the email messages.</h2>");
        out.println(exc.toString());

    } finally {
        try {
            if (folder != null)
                folder.close(false);

            if (popStore != null)
                popStore.close();
        } catch (Exception e) {
        }
    }
}

From source file:com.qwazr.library.email.EmlParser.java

@Override
public void parseContent(final MultivaluedMap<String, String> parameters, final InputStream inputStream,
        final String extension, final String mimeType, final ParserResultBuilder resultBuilder)
        throws Exception {
    final Session session = Session.getDefaultInstance(JAVAMAIL_PROPS);

    resultBuilder.metas().set(MIME_TYPE, findMimeType(extension, mimeType, this::findMimeTypeUsingDefault));

    final MimeMessage mimeMessage = new MimeMessage(session, inputStream);
    final MimeMessageParser mimeMessageParser = new MimeMessageParser(mimeMessage).parse();

    ParserFieldsBuilder document = resultBuilder.newDocument();
    final String from = mimeMessageParser.getFrom();
    if (from != null)
        document.add(FROM, from);/*  w  w  w  .  j  ava2s .  c  om*/
    for (Address address : mimeMessageParser.getTo())
        document.add(RECIPIENT_TO, address.toString());
    for (Address address : mimeMessageParser.getCc())
        document.add(RECIPIENT_CC, address.toString());
    for (Address address : mimeMessageParser.getBcc())
        document.add(RECIPIENT_BCC, address.toString());
    document.add(SUBJECT, mimeMessageParser.getSubject());
    document.add(HTML_CONTENT, mimeMessageParser.getHtmlContent());
    document.add(PLAIN_CONTENT, mimeMessageParser.getPlainContent());
    document.add(SENT_DATE, mimeMessage.getSentDate());
    document.add(RECEIVED_DATE, mimeMessage.getReceivedDate());

    for (DataSource dataSource : mimeMessageParser.getAttachmentList()) {
        document.add(ATTACHMENT_NAME, dataSource.getName());
        document.add(ATTACHMENT_TYPE, dataSource.getContentType());
        // TODO Extract content from attachmend
        // if (parserSelector != null) {
        // Parser attachParser = parserSelector.parseStream(
        // getSourceDocument(), dataSource.getName(),
        // dataSource.getContentType(), null,
        // dataSource.getInputStream(), null, null, null);
        // if (attachParser != null) {
        // List<ParserResultItem> parserResults = attachParser
        // .getParserResults();
        // if (parserResults != null)
        // for (ParserResultItem parserResult : parserResults)
        // result.addField(
        // ParserFieldEnum.email_attachment_content,
        // parserResult);
        // }
        // }
    }
    if (StringUtils.isEmpty(mimeMessageParser.getHtmlContent()))
        document.add(LANG_DETECTION, languageDetection(document, PLAIN_CONTENT, 10000));
    else
        document.add(LANG_DETECTION, languageDetection(document, HTML_CONTENT, 10000));
}