Example usage for javax.mail.internet MimeMessage setSentDate

List of usage examples for javax.mail.internet MimeMessage setSentDate

Introduction

In this page you can find the example usage for javax.mail.internet MimeMessage setSentDate.

Prototype

@Override
public void setSentDate(Date d) throws MessagingException 

Source Link

Document

Set the RFC 822 "Date" header field.

Usage

From source file:org.jumpmind.metl.core.runtime.flow.FlowRuntime.java

protected void sendNotifications(Notification.EventType eventType) {
    if (notifications != null && notifications.size() > 0) {
        Transport transport = null;/*from   ww w. ja v  a  2s.co  m*/
        Date date = new Date();
        flowParameters.put("_date", DateFormatUtils.format(date, DATE_FORMAT));
        flowParameters.put("_time", DateFormatUtils.format(date, TIME_FORMAT));

        try {
            for (Notification notification : notifications) {
                if (notification.getEventType().equals(eventType.toString())) {
                    log.info("Sending notification '" + notification.getName() + "' of level '"
                            + notification.getLevel() + "' and type '" + notification.getNotifyType() + "'");
                    transport = mailSession.getTransport();
                    MimeMessage message = new MimeMessage(mailSession.getSession());
                    message.setSentDate(new Date());
                    message.setRecipients(RecipientType.BCC, notification.getRecipients());
                    message.setSubject(
                            FormatUtils.replaceTokens(notification.getSubject(), flowParameters, true));
                    message.setText(FormatUtils.replaceTokens(notification.getMessage(), flowParameters, true));
                    try {
                        transport.sendMessage(message, message.getAllRecipients());
                    } catch (MessagingException e) {
                        log.error("Failure while sending notification", e);
                    }
                }
            }
        } catch (MessagingException e) {
            log.error("Failure while preparing notification", e);
        } finally {
            mailSession.closeTransport(transport);
        }
    }
}

From source file:com.predic8.membrane.core.interceptor.authentication.session.EmailTokenProvider.java

private void sendEmail(String sender, String recipient, String subject, String text) {
    try {/*from  w  w  w.  j  a va2s  .  c  o m*/
        Properties props = System.getProperties();
        props.put("mail.smtp.port", "" + smtpPort);
        props.put("mail.smtp.socketFactory.port", "" + smtpPort);
        if (ssl) {
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.starttls.required", "true");
        }
        if (smtpUser != null) {
            props.put("mail.smtp.auth", "true");
        }

        Session session = Session.getInstance(props, null);

        final MimeMessage msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(sender));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient, false));
        msg.setSubject(subject);
        msg.setText(text, Constants.UTF_8);
        msg.setSentDate(new Date());

        SMTPTransport t = (SMTPTransport) session.getTransport(ssl ? "smtps" : "smtp");
        t.connect(smtpHost, smtpUser, smtpPassword);
        t.sendMessage(msg, msg.getAllRecipients());
        t.close();
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

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

/**
 * Actually send the given array of MimeMessages via JavaMail.
 * @param mimeMessages MimeMessage objects to send
 * @param originalMessages corresponding original message objects
 * that the MimeMessages have been created from (with same array
 * length and indices as the "mimeMessages" array), if any
 * @throws org.springframework.mail.MailAuthenticationException
 * in case of authentication failure//from   ww w .ja  va  2s. co m
 * @throws org.springframework.mail.MailSendException
 * in case of failure when sending a message
 */
protected void doSend(MimeMessage[] mimeMessages, Object[] originalMessages) throws MailException {
    Map failedMessages = new HashMap();
    try {
        Transport transport = getTransport(getSession());
        transport.connect(getHost(), getPort(), getUsername(), getPassword());
        try {
            for (int i = 0; i < mimeMessages.length; i++) {
                MimeMessage mimeMessage = mimeMessages[i];
                try {
                    if (mimeMessage.getSentDate() == null) {
                        mimeMessage.setSentDate(new Date());
                    }
                    mimeMessage.saveChanges();
                    transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
                } catch (MessagingException ex) {
                    Object original = (originalMessages != null ? originalMessages[i] : mimeMessage);
                    failedMessages.put(original, ex);
                }
            }
        } finally {
            transport.close();
        }
    } catch (AuthenticationFailedException ex) {
        throw new MailAuthenticationException(ex);
    } catch (MessagingException ex) {
        throw new MailSendException("Mail server connection failed", ex);
    }
    if (!failedMessages.isEmpty()) {
        throw new MailSendException(failedMessages);
    }
}

From source file:org.awknet.commons.mail.Mail.java

public void send() throws AddressException, MessagingException, FileNotFoundException, IOException {
    int count = recipientsTo.size() + recipientsCc.size() + recipientsBcc.size();
    if (count == 0)
        return;/*from  w w  w. j ava 2s .  c o m*/

    deleteDuplicates();

    Properties javaMailProperties = new Properties();

    if (fileName.equals("") || fileName == null)
        fileName = DEFAULT_PROPERTIES_FILE;

    javaMailProperties.load(getClass().getResourceAsStream(fileName));

    final String mailUsername = javaMailProperties.getProperty("mail.autentication.username");
    final String mailPassword = javaMailProperties.getProperty("mail.autentication.password");
    final String mailFrom = javaMailProperties.getProperty("mail.autentication.mail_from");

    Session session = Session.getInstance(javaMailProperties, new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(mailUsername, mailPassword);
        }
    });

    final MimeMessage msg = new MimeMessage(session);

    msg.setFrom(new InternetAddress(mailFrom));
    msg.setRecipients(Message.RecipientType.TO, getToRecipientsArray());
    msg.setRecipients(Message.RecipientType.CC, getCcRecipientsArray());
    msg.setRecipients(Message.RecipientType.BCC, getBccRecipientsArray());
    msg.setSentDate(new Date());
    msg.setSubject(mailSubject);
    msg.setText(mailText, "UTF-8", "html");
    // msg.setText(mailText); //OLD WAY
    new Thread(new Runnable() {
        public void run() {
            try {
                Transport.send(msg);
                Logger.getLogger(Mail.class.getName()).log(Level.INFO, "email was sent successfully!");
            } catch (MessagingException ex) {
                Logger.getLogger(Mail.class.getName()).log(Level.SEVERE, "Cant send email!", ex);
            }
        }
    }).start();
}

From source file:jenkins.plugins.mailer.tasks.MimeMessageBuilder.java

/**
 * Build a {@link MimeMessage} instance from the set of supplied parameters.
 * @return The {@link MimeMessage} instance;
 * @throws MessagingException/*from   w  w w .  java2  s  . c  o  m*/
 * @throws UnsupportedEncodingException
 */
public MimeMessage buildMimeMessage() throws MessagingException, UnsupportedEncodingException {
    MimeMessage msg = new MimeMessage(Mailer.descriptor().createSession());

    setJenkinsInstanceIdent(msg);

    msg.setContent("", contentType());
    if (StringUtils.isNotBlank(from)) {
        msg.setFrom(toNormalizedAddress(from));
    }
    msg.setSentDate(new Date());

    addSubject(msg);
    addBody(msg);
    addRecipients(msg);

    if (!replyTo.isEmpty()) {
        msg.setReplyTo(toAddressArray(replyTo));
    }
    return msg;
}

From source file:org.apache.james.mailetcontainer.impl.JamesMailetContext.java

/**
 * Generates a bounce mail that is a bounce of the original message.
 *
 * @param bounceText the text to be prepended to the message to describe the bounce
 *                   condition//from w  ww  .j  av  a2 s .  co m
 * @return the bounce mail
 * @throws MessagingException if the bounce mail could not be created
 */
private MailImpl rawBounce(Mail mail, String bounceText) throws MessagingException {
    // This sends a message to the james component that is a bounce of the
    // sent message
    MimeMessage original = mail.getMessage();
    MimeMessage reply = (MimeMessage) original.reply(false);
    reply.setSubject("Re: " + original.getSubject());
    reply.setSentDate(new Date());
    Collection<MailAddress> recipients = new HashSet<MailAddress>();
    recipients.add(mail.getSender());
    InternetAddress addr[] = { new InternetAddress(mail.getSender().toString()) };
    reply.setRecipients(Message.RecipientType.TO, addr);
    reply.setFrom(new InternetAddress(mail.getRecipients().iterator().next().toString()));
    reply.setText(bounceText);
    reply.setHeader(RFC2822Headers.MESSAGE_ID, "replyTo-" + mail.getName());
    return new MailImpl("replyTo-" + mail.getName(),
            new MailAddress(mail.getRecipients().iterator().next().toString()), recipients, reply);
}

From source file:hudson.tasks.mail.impl.BaseBuildResultMail.java

/**
 * Creates empty mail./*from   w w w  . jav  a 2s .c om*/
 *
 * @param build build.
 * @param listener listener.
 * @return empty mail.
 * @throws MessagingException exception if any.
 */
protected MimeMessage createEmptyMail(AbstractBuild<?, ?> build, BuildListener listener)
        throws MessagingException {
    MimeMessage msg = new HudsonMimeMessage(Mailer.descriptor().createSession());
    // TODO: I'd like to put the URL to the page in here,
    // but how do I obtain that?
    msg.setContent("", "text/plain");
    msg.setFrom(new InternetAddress(Mailer.descriptor().getAdminAddress()));
    msg.setSentDate(new Date());

    Set<InternetAddress> rcp = new LinkedHashSet<InternetAddress>();
    StringTokenizer tokens = new StringTokenizer(getRecipients());
    while (tokens.hasMoreTokens()) {
        String address = tokens.nextToken();
        if (address.startsWith("upstream-individuals:")) {
            // people who made a change in the upstream
            String projectName = address.substring("upstream-individuals:".length());
            AbstractProject up = Hudson.getInstance().getItemByFullName(projectName, AbstractProject.class);
            if (up == null) {
                listener.getLogger().println("No such project exist: " + projectName);
                continue;
            }
            includeCulpritsOf(up, build, listener, rcp);
        } else {
            // ordinary address
            try {
                rcp.add(new InternetAddress(address));
            } catch (AddressException e) {
                // report bad address, but try to send to other addresses
                e.printStackTrace(listener.error(e.getMessage()));
            }
        }
    }

    if (CollectionUtils.isNotEmpty(upstreamProjects)) {
        for (AbstractProject project : upstreamProjects) {
            includeCulpritsOf(project, build, listener, rcp);
        }
    }

    if (sendToIndividuals) {
        Set<User> culprits = build.getCulprits();

        if (debug)
            listener.getLogger()
                    .println("Trying to send e-mails to individuals who broke the build. sizeof(culprits)=="
                            + culprits.size());

        rcp.addAll(buildCulpritList(listener, culprits));
    }
    msg.setRecipients(Message.RecipientType.TO, rcp.toArray(new InternetAddress[rcp.size()]));

    AbstractBuild<?, ?> pb = build.getPreviousBuild();
    if (pb != null) {
        MailMessageIdAction b = pb.getAction(MailMessageIdAction.class);
        if (b != null) {
            msg.setHeader("In-Reply-To", b.messageId);
            msg.setHeader("References", b.messageId);
        }
    }

    return msg;
}

From source file:org.cgiar.ccafs.marlo.action.TestSMTPAction.java

@Override
public String execute() throws Exception {

    Properties properties = System.getProperties();
    properties.put("mail.smtp.host", config.getEmailHost());
    properties.put("mail.smtp.port", config.getEmailPort());

    Session session = Session.getInstance(properties, new Authenticator() {

        @Override//from ww w.ja v  a 2 s. c  o  m
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(config.getEmailUsername(), config.getEmailPassword());
        }
    });

    // Create a new message
    MimeMessage msg = new MimeMessage(session) {

        @Override
        protected void updateMessageID() throws MessagingException {
            if (this.getHeader("Message-ID") == null) {
                super.updateMessageID();
            }
        }
    };

    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("h.jimenez@cgiar.org", false));
    msg.setSubject("Test email");
    msg.setSentDate(new Date());
    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent("If you receive this email, it means that the server is working correctly.",
            "text; charset=utf-8");

    Thread thread = new Thread() {

        @Override
        public void run() {

            sent = false;
            int i = 0;
            while (!sent) {
                try {
                    Transport.send(sendMail);
                    LOG.info("Message sent TRIED#: " + i + " \n" + "Test email");
                    sent = true;

                } catch (MessagingException e) {
                    LOG.info("Message  DON'T sent: \n" + "Test email");

                    i++;
                    if (i == 10) {
                        break;

                    }
                    try {
                        Thread.sleep(1 * // minutes to sleep
                        60 * // seconds to a minute
                        1000);
                    } catch (InterruptedException e1) {

                        e1.printStackTrace();
                    }
                    e.printStackTrace();
                }

            }

        };
    };

    thread.run();

    if (sent) {
        return SUCCESS;
    } else {
        return INPUT;
    }
}

From source file:ee.cyber.licensing.service.MailService.java

public void sendExpirationNearingMail(License license) throws IOException, MessagingException {
    logger.info("1st ===> setup Mail Server Properties");
    Properties mailServerProperties = getProperties();

    final String email = mailServerProperties.getProperty("fromEmail");
    final String password = mailServerProperties.getProperty("password");
    final String host = mailServerProperties.getProperty("mail.smtp.host");
    final String mailTo = mailServerProperties.getProperty("mailTo");

    logger.info("2nd ===> create Authenticator object to pass in Session.getInstance argument");

    Authenticator authentication = new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(email, password);
        }//w w  w . j av  a  2 s . c om
    };
    logger.info("Mail Server Properties have been setup successfully");

    logger.info("3rd ===> get Mail Session..");
    Session getMailSession = Session.getInstance(mailServerProperties, authentication);

    logger.info("4th ===> generateAndSendEmail() starts");
    MimeMessage mailMessage = new MimeMessage(getMailSession);

    mailMessage.addHeader("Content-type", "text/html; charset=UTF-8");
    mailMessage.addHeader("format", "flowed");
    mailMessage.addHeader("Content-Transfer-Encoding", "8bit");

    mailMessage.setFrom(new InternetAddress(email, "Licensing service"));
    mailMessage.setSubject("License with id " + license.getId() + " is expiring");
    mailMessage.setSentDate(new Date());
    mailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
    String emailBody = "This is test<br><br> Regards, <br>Licensing team";
    mailMessage.setContent(emailBody, "text/html");

    logger.info("5th ===> Get Session");
    sendMail(email, password, host, getMailSession, mailMessage);

}

From source file:com.mobileman.projecth.business.impl.MailManagerImpl.java

/**
 * @param mimeMessage//w w  w. j a va  2s.  c  o  m
 * @throws MessagingException
 */
private void prepareMessage(MimeMessage mimeMessage) throws MessagingException {
    if (log.isDebugEnabled()) {
        log.debug("prepareMessage(MimeMessage) - start"); //$NON-NLS-1$
    }

    mimeMessage.addHeader("Content-Type", "text/plain;charset=UTF-8");
    mimeMessage.setSentDate(new Date());

    if (log.isDebugEnabled()) {
        log.debug("prepareMessage(MimeMessage) - returns"); //$NON-NLS-1$
    }
}