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:com.emc.plants.service.impl.MailerBean.java

/** 
 * Create a mail message and send it./*w  w  w .ja v a  2s  .  com*/
 *
 * @param customerInfo  Customer information.
 * @param orderKey
 * @throws MailerAppException
 */
public void createAndSendMail(CustomerInfo customerInfo, long orderKey) throws MailerAppException {
    try {
        EMailMessage eMessage = new EMailMessage(createSubjectLine(orderKey), createMessage(orderKey),
                customerInfo.getCustomerID());
        Util.debug("Sending message" + "\nTo: " + eMessage.getEmailReceiver() + "\nSubject: "
                + eMessage.getSubject() + "\nContents: " + eMessage.getHtmlContents());

        //Session mailSession = (Session) Util.getInitialContext().lookup(MAIL_SESSION);

        MimeMessage msg = new MimeMessage(mailSession);
        msg.setFrom();

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(eMessage.getEmailReceiver(), false));

        msg.setSubject(eMessage.getSubject());
        MimeBodyPart mbp = new MimeBodyPart();
        mbp.setText(eMessage.getHtmlContents(), "us-ascii");
        msg.setHeader("X-Mailer", "JavaMailer");
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp);
        msg.setContent(mp);
        msg.setSentDate(new Date());

        Transport.send(msg);

        Util.debug("\nMail sent successfully.");
    } catch (Exception e) {
        Util.debug("Error sending mail. Have mail resources been configured correctly?");
        Util.debug("createAndSendMail exception : " + e);
        e.printStackTrace();
        throw new MailerAppException("Failure while sending mail");
    }
}

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

/**
 * Sends email with attachments/*from w w w.  java 2s .c  om*/
 * 
 * @param from
 *        The address this message is to be listed as coming from.
 * @param to
 *        The address(es) this message should be sent to.
 * @param subject
 *        The subject of this message.
 * @param content
 *        The body of the message.
 * @param headerToStr
 *        If specified, this is placed into the message header, but "to" is used for the recipients.
 * @param replyTo
 *        If specified, this is the reply to header address(es).
 * @param additionalHeaders
 *        Additional email headers to send (List of String). For example, content type or forwarded headers (may be null)        
 * @param messageAttachments
 *         Message attachments
 */
protected void sendMailWithAttachments(InternetAddress from, InternetAddress[] to, String subject,
        String content, InternetAddress[] headerTo, InternetAddress[] replyTo, List<String> additionalHeaders,
        List<EmailAttachment> emailAttachments) {
    if (testMode) {
        testSendMail(from, to, subject, content, headerTo, replyTo, additionalHeaders, emailAttachments);
        return;
    }

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

    if (from == null) {
        if (logger.isWarnEnabled()) {
            logger.warn("sendMail: from is needed to send email");
        }
        return;
    }

    if (to == null) {
        if (logger.isWarnEnabled()) {
            logger.warn("sendMail: to is needed to send email");
        }
        return;
    }

    if (content == null) {
        if (logger.isWarnEnabled()) {
            logger.warn("sendMail: content is needed to send email");
        }
        return;
    }

    if (emailAttachments == null || emailAttachments.size() == 0) {
        if (logger.isWarnEnabled()) {
            logger.warn("sendMail: emailAttachments are needed to send email with attachments");
        }
        return;
    }

    try {
        if (session == null) {
            if (logger.isWarnEnabled()) {
                logger.warn("mail session is null");
            }
            return;

        }
        MimeMessage message = new MimeMessage(session);

        // default charset
        String charset = "UTF-8";

        message.setSentDate(new Date());
        message.setFrom(from);
        message.setSubject(subject, charset);

        MimeBodyPart messageBodyPart = new MimeBodyPart();

        // Content-Type: text/plain; text/html;
        String contentType = null, contentTypeValue = null;

        if (additionalHeaders != null) {
            for (String header : additionalHeaders) {
                if (header.toLowerCase().startsWith("content-type:")) {
                    contentType = header;

                    contentTypeValue = contentType.substring(
                            contentType.indexOf("content-type:") + "content-type:".length(),
                            contentType.length());
                    break;
                }
            }
        }

        // message
        String messagetype = "";
        if ((contentTypeValue != null) && (contentTypeValue.trim().equalsIgnoreCase("text/html"))) {
            messagetype = "text/html; charset=" + charset;
            messageBodyPart.setContent(content, messagetype);
        } else {

            messagetype = "text/plain; charset=" + charset;
            messageBodyPart.setContent(content, messagetype);
        }

        //messageBodyPart.setContent(content, "text/html; charset="+ charset);

        Multipart multipart = new MimeMultipart();

        multipart.addBodyPart(messageBodyPart);

        String jforumAttachmentStoreDir = serverConfigurationService()
                .getString(JForumAttachmentService.ATTACHMENTS_STORE_DIR);
        if (jforumAttachmentStoreDir == null || jforumAttachmentStoreDir.trim().length() == 0) {
            if (logger.isWarnEnabled()) {
                logger.warn("JForum attachments directory (" + JForumAttachmentService.ATTACHMENTS_STORE_DIR
                        + ") property is not set in sakai.properties ");
            }
        } else {
            // attachments
            for (EmailAttachment emailAttachment : emailAttachments) {

                String filePath = jforumAttachmentStoreDir + "/" + emailAttachment.getPhysicalFileName();

                messageBodyPart = new MimeBodyPart();
                DataSource source = new FileDataSource(filePath);
                try {
                    messageBodyPart.setDataHandler(new DataHandler(source));
                    messageBodyPart.setFileName(emailAttachment.getRealFileName());

                    multipart.addBodyPart(messageBodyPart);
                } catch (MessagingException e) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Error while attaching attachments: " + e, e);
                    }
                }
            }
        }

        message.setContent(multipart);

        Transport.send(message, to);

    } catch (MessagingException e) {
        if (logger.isWarnEnabled()) {
            logger.warn("sendMail: Error in sending email: " + e, e);
        }
    }
}

From source file:au.org.paperminer.main.UserFilter.java

/**
 * Sends an email to the user asking they follow a link to validate their email address
 * @param id DB key to be embedded in response link
 * @param email Address target// www.  j  a  v  a2 s . c  o m
 */
private void sendVerificationEmail(String id, String email, ServletRequest req) {
    m_logger.debug("sending mail");
    String from = "admin@" + m_serverName;
    Properties props = new Properties();
    props.put("mail.smpt.host", m_serverName);
    props.put("mail.from", from);
    Session session = Session.getInstance(props, null);
    try {
        MimeMessage msg = new MimeMessage(session);
        msg.setRecipients(Message.RecipientType.TO, email);
        msg.setSubject("Verify your PaperMiner email address");
        msg.setSentDate(new Date());
        // FIXME: the verify address needs to be more robust
        msg.setText("Dear " + email.substring(0, email.indexOf("@")) + ",\n\n"
                + "PaperMiner has sent you this message to validate that the email address which you "
                + "supplied is able to receive notifications from our server.\n"
                + "To complete the verification process, please click the link below.\n\n" + "http://"
                + m_serverName + ":8080/PaperMiner/pm/vfy?id=" + id + "\n\n"
                + "If you are unable to click the link above, verification can be completed by copying "
                + "and pasting it into the address bar of your web browser.\n\n" + "Your email address is "
                + email + ". Use this to log in when returning to the PaperMiner site.\n"
                + "You can update your email address, or change your TROVE API key at any time through the "
                + "\"Manage Your Details\" option of the User menu, but an email change will require re-validation.\n\n"
                + "Paper Miner Administrator");
        Transport.send(msg);
        m_logger.info("Verifcation mail sent to " + email);
    } catch (MessagingException ex) {
        m_logger.error("Email verification to " + email + " failed", ex);
        req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e109");
    }
}

From source file:org.xwiki.commons.internal.DefaultMailSender.java

@Override
public int send(Mail mail) {
    Session session = null;//from   w  ww .  jav  a2s .co m
    Transport transport = null;
    if ((mail.getTo() == null || StringUtils.isEmpty(mail.getTo()))
            && (mail.getCc() == null || StringUtils.isEmpty(mail.getCc()))
            && (mail.getBcc() == null || StringUtils.isEmpty(mail.getBcc()))) {
        logger.error("This mail has no recipient");
        return 0;
    }
    if (mail.getContents().size() == 0) {
        logger.error("This mail is empty. You should add a content");
        return 0;
    }
    try {
        if ((transport == null) || (session == null)) {
            logger.info("Sending mail : Initializing properties");
            Properties props = initProperties();
            session = Session.getInstance(props, null);
            transport = session.getTransport("smtp");
            if (session.getProperty("mail.smtp.auth") == "true")
                transport.connect(session.getProperty("mail.smtp.server.username"),
                        session.getProperty("mail.smtp.server.password"));
            else
                transport.connect();
            try {
                Multipart wrapper = generateMimeMultipart(mail);
                InternetAddress[] adressesTo = this.toInternetAddresses(mail.getTo());
                MimeMessage message = new MimeMessage(session);
                message.setSentDate(new Date());
                message.setSubject(mail.getSubject());
                message.setFrom(new InternetAddress(mail.getFrom()));
                message.setRecipients(javax.mail.Message.RecipientType.TO, adressesTo);
                if (mail.getReplyTo() != null && !StringUtils.isEmpty(mail.getReplyTo())) {
                    logger.info("Adding ReplyTo field");
                    InternetAddress[] adressesReplyTo = this.toInternetAddresses(mail.getReplyTo());
                    if (adressesReplyTo.length != 0)
                        message.setReplyTo(adressesReplyTo);
                }
                if (mail.getCc() != null && !StringUtils.isEmpty(mail.getCc())) {
                    logger.info("Adding Cc recipients");
                    InternetAddress[] adressesCc = this.toInternetAddresses(mail.getCc());
                    if (adressesCc.length != 0)
                        message.setRecipients(javax.mail.Message.RecipientType.CC, adressesCc);
                }
                if (mail.getBcc() != null && !StringUtils.isEmpty(mail.getBcc())) {
                    InternetAddress[] adressesBcc = this.toInternetAddresses(mail.getBcc());
                    if (adressesBcc.length != 0)
                        message.setRecipients(javax.mail.Message.RecipientType.BCC, adressesBcc);
                }
                message.setContent(wrapper);
                message.setSentDate(new Date());
                transport.sendMessage(message, message.getAllRecipients());
                transport.close();
            } catch (SendFailedException sfex) {
                logger.error("Error encountered while trying to send the mail");
                logger.error("SendFailedException has occured.", sfex);
                try {
                    transport.close();
                } catch (MessagingException Mex) {
                    logger.error("MessagingException has occured.", Mex);
                }
                return 0;
            } catch (MessagingException mex) {
                logger.error("Error encountered while trying to send the mail");
                logger.error("MessagingException has occured.", mex);

                try {
                    transport.close();
                } catch (MessagingException ex) {
                    logger.error("MessagingException has occured.", ex);
                }
                return 0;
            }
        }
    } catch (Exception e) {
        System.out.println(e.toString());
        logger.error("Error encountered while trying to setup mail properties");
        try {
            if (transport != null) {
                transport.close();
            }
        } catch (MessagingException ex) {
            logger.error("MessagingException has occured.", ex);
        }
        return 0;
    }

    return 1;
}

From source file:com.cosmicpush.plugins.smtp.EmailMessage.java

/**
 * @param session the applications current session.
 * @throws EmailMessageException in response to any other type of exception.
 *///from   ww  w.  j av a 2 s . co m
@SuppressWarnings({ "ConstantConditions" })
protected void send(Session session) throws EmailMessageException {
    try {

        // create a message
        MimeMessage msg = new MimeMessage(session);

        //set some of the basic attributes.
        msg.setFrom(fromAddress);
        msg.setRecipients(Message.RecipientType.TO, ReflectUtils.toArray(InternetAddress.class, toAddresses));
        msg.setSubject(subject);
        msg.setSentDate(new Date());

        if (replyToAddress.isEmpty() == false) {
            msg.setReplyTo(ReflectUtils.toArray(InternetAddress.class, replyToAddress));
        }

        // create the Multipart and add set it as the content of the message
        Multipart multipart = new MimeMultipart();
        msg.setContent(multipart);

        // create and fill the HTML part of the messgae if it exists
        if (html != null) {
            MimeBodyPart bodyPart = new MimeBodyPart();
            bodyPart.setText(html, "UTF-8", "html");
            multipart.addBodyPart(bodyPart);
        }

        // create and fill the text part of the messgae if it exists
        if (text != null) {
            MimeBodyPart bodyPart = new MimeBodyPart();
            bodyPart.setText(text, "UTF-8", "plain");
            multipart.addBodyPart(bodyPart);
        }

        if (html == null && text == null) {
            MimeBodyPart bodyPart = new MimeBodyPart();
            bodyPart.setText("", "UTF-8", "plain");
            multipart.addBodyPart(bodyPart);
        }

        // remove any nulls from the list of attachments.
        while (attachments.remove(null)) {
            /* keep going */ }

        // Attach any files that we have, making sure that they exist first
        for (File file : attachments) {
            if (file.exists() == false) {
                throw new EmailMessageException("The file \"" + file.getAbsolutePath() + "\" does not exist.");
            } else {
                MimeBodyPart attachmentPart = new MimeBodyPart();
                attachmentPart.attachFile(file);
                multipart.addBodyPart(attachmentPart);
            }
        }

        // send the message
        Transport.send(msg);

    } catch (EmailMessageException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new EmailMessageException("Exception sending email\n" + toString(), ex);
    }
}

From source file:org.pentaho.platform.plugin.services.email.EmailService.java

/**
 * Tests the provided email configuration by sending a test email. This will just indicate that the server
 * configuration is correct and a test email was successfully sent. It does not test the destination address.
 * /*from w w w .j  a v a2 s  .  co  m*/
 * @param emailConfig
 *          the email configuration to test
 * @throws Exception
 *           indicates an error running the test (as in an invalid configuration)
 */
public String sendEmailTest(final IEmailConfiguration emailConfig) {
    final Properties emailProperties = new Properties();
    emailProperties.setProperty("mail.smtp.host", emailConfig.getSmtpHost());
    emailProperties.setProperty("mail.smtp.port", ObjectUtils.toString(emailConfig.getSmtpPort()));
    emailProperties.setProperty("mail.transport.protocol", emailConfig.getSmtpProtocol());
    emailProperties.setProperty("mail.smtp.starttls.enable", ObjectUtils.toString(emailConfig.isUseStartTls()));
    emailProperties.setProperty("mail.smtp.auth", ObjectUtils.toString(emailConfig.isAuthenticate()));
    emailProperties.setProperty("mail.smtp.ssl", ObjectUtils.toString(emailConfig.isUseSsl()));
    emailProperties.setProperty("mail.debug", ObjectUtils.toString(emailConfig.isDebug()));

    Session session = null;
    if (emailConfig.isAuthenticate()) {
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(emailConfig.getUserId(), emailConfig.getPassword());
            }
        };
        session = Session.getInstance(emailProperties, authenticator);
    } else {
        session = Session.getInstance(emailProperties);
    }

    String sendEmailMessage = "";
    try {
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(emailConfig.getDefaultFrom(), emailConfig.getFromName()));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailConfig.getDefaultFrom()));
        msg.setSubject(messages.getString("EmailService.SUBJECT"));
        msg.setText(messages.getString("EmailService.MESSAGE"));
        msg.setHeader("X-Mailer", "smtpsend");
        msg.setSentDate(new Date());
        Transport.send(msg);
        sendEmailMessage = "EmailTester.SUCESS";
    } catch (Exception e) {
        logger.error(messages.getString("EmailService.NOT_CONFIGURED"), e);
        sendEmailMessage = "EmailTester.FAIL";
    }
    return sendEmailMessage;
}

From source file:eu.optimis.sm.gui.server.ServiceManagerWebServiceImpl.java

public static void Send(final String username, final String password, String recipientEmail, String ccEmail,
        String title, String message) throws AddressException, MessagingException {
    final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

    Properties props = System.getProperties();
    props.setProperty("mail.smtps.host", "smtp.gmail.com");
    props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
    props.setProperty("mail.smtp.socketFactory.fallback", "false");
    props.setProperty("mail.smtp.port", "465");
    props.setProperty("mail.smtp.socketFactory.port", "465");
    props.setProperty("mail.smtps.auth", "true");

    props.put("mail.smtps.quitwait", "false");

    Session session = Session.getInstance(props, null);
    final MimeMessage msg = new MimeMessage(session);

    msg.setFrom(new InternetAddress(username + "@gmail.com"));
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false));

    if (ccEmail.length() > 0) {
        msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccEmail, false));
    }/*from w w w  .  jav a2 s.c  om*/

    msg.setSubject(title);
    msg.setText(message, "utf-8");
    msg.setSentDate(new Date());

    SMTPTransport t = (SMTPTransport) session.getTransport("smtps");
    t.connect("smtp.gmail.com", username, password);
    t.sendMessage(msg, msg.getAllRecipients());
    t.close();
}

From source file:de.tuttas.servlets.MailSender.java

private void transmitMail(MailObject mo) throws MessagingException {

    // creates a new session with an authenticator
    Authenticator auth = new Authenticator() {
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(Config.getInstance().user, Config.getInstance().pass);
        }/*from  w ww  .j av a  2 s .com*/
    };
    Session session = Session.getInstance(properties, auth);
    // creates a new e-mail message
    MimeMessage msg = new MimeMessage(session);

    msg.setFrom(new InternetAddress(mo.getFrom()));
    InternetAddress[] toAddresses = mo.getRecipient();
    msg.setRecipients(Message.RecipientType.TO, toAddresses);
    InternetAddress[] bccAdresses = mo.getBcc();
    InternetAddress[] ccAdresses = mo.getCC();

    if (bccAdresses[0] != null)
        msg.setRecipients(Message.RecipientType.BCC, bccAdresses);
    if (ccAdresses[0] != null)
        msg.setRecipients(Message.RecipientType.CC, ccAdresses);
    msg.setSubject(mo.getSubject(), "UTF-8");

    msg.setSentDate(new Date());
    msg.setContent(mo.getContent(), "text/plain; charset=UTF-8");
    // sends the e-mail
    // TODO Kommentar entfernen
    Transport.send(msg);
}

From source file:de.saly.elasticsearch.imap.AbstractIMAPRiverUnitTest.java

protected void putMailInMailbox(final int messages) throws MessagingException {

    for (int i = 0; i < messages; i++) {
        final MimeMessage message = new MimeMessage((Session) null);
        message.setFrom(new InternetAddress(EMAIL_TO));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(EMAIL_USER_ADDRESS));
        message.setSubject(EMAIL_SUBJECT + "::" + i);
        message.setText(EMAIL_TEXT + "::" + SID++);
        message.setSentDate(new Date());
        MockMailbox.get(EMAIL_USER_ADDRESS).getInbox().add(message);
    }/*from   w ww .  j  a  v a  2s.  co m*/

    logger.info("Putted " + messages + " into mailbox " + EMAIL_USER_ADDRESS);
}

From source file:de.saly.elasticsearch.imap.AbstractIMAPRiverUnitTest.java

protected void putMailInMailbox2(final int messages) throws MessagingException {

    for (int i = 0; i < messages; i++) {
        final MimeMessage message = new MimeMessage((Session) null);
        message.setFrom(new InternetAddress(EMAIL_TO));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(EMAIL_USER_ADDRESS2));
        message.setSubject(EMAIL_SUBJECT + "::" + i);
        message.setText(EMAIL_TEXT + "::" + SID++);
        message.setSentDate(new Date());
        MockMailbox.get(EMAIL_USER_ADDRESS2).getInbox().add(message);
    }//from w  ww  .  j a va 2 s. c o  m

    logger.info("Putted " + messages + " into mailbox " + EMAIL_USER_ADDRESS2);
}