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.enjoyxstudy.selenium.autoexec.mail.MailSender.java

/**
 * @param mimeMessage/*  ww  w .  j a  v  a2 s  .co m*/
 * @throws MessagingException
 */
private void _send(MimeMessage mimeMessage) throws MessagingException {

    Transport transport = null;

    try {

        transport = session.getTransport();
        transport.connect();

        mimeMessage.setSentDate(new Date());
        mimeMessage.saveChanges();

        transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
    } finally {
        if (transport != null && transport.isConnected()) {
            transport.close();
        }
    }
}

From source file:com.consol.citrus.demo.devoxx.service.MailService.java

/**
 * Send mail via SMTP connection./*  ww  w .j  a  va  2  s .  co m*/
 * @param to
 * @param subject
 * @param body
 */
public void sendMail(String to, String subject, String body) {
    Properties props = new Properties();
    props.put("mail.smtp.host", mailServerHost);
    props.put("mail.smtp.port", mailServerPort);
    props.put("mail.smtp.auth", true);

    Authenticator authenticator = new Authenticator() {
        private PasswordAuthentication pa = new PasswordAuthentication(username, password);

        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            return pa;
        }
    };

    Session session = Session.getInstance(props, authenticator);
    session.setDebug(true);
    MimeMessage message = new MimeMessage(session);
    try {
        message.setFrom(new InternetAddress(from));
        InternetAddress[] address = { new InternetAddress(to) };
        message.setRecipients(Message.RecipientType.TO, address);
        message.setSubject(subject);
        message.setSentDate(new Date());
        message.setText(body);
        Transport.send(message);
    } catch (MessagingException e) {
        log.error("Failed to send mail!", e);
    }
}

From source file:com.aurel.track.util.emailHandling.MailBuilder.java

private MimeMessage prepareHTMLMimeMessage(InternetAddress internetAddressFrom, String subject, String htmlBody,
        List<LabelValueBean> attachments) throws Exception {
    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(internetAddressFrom);//ww  w . j a  va  2s  .co  m
    msg.setHeader(XMAILER, xmailer);
    msg.setSubject(subject.trim(), mailEncoding);
    msg.setSentDate(new Date());

    MimeMultipart mimeMultipart = new MimeMultipart("related");

    BodyPart messageBodyPart = new MimeBodyPart();
    //Euro sign finally, shown correctly
    messageBodyPart.setContent(htmlBody, "text/html;charset=" + mailEncoding);
    mimeMultipart.addBodyPart(messageBodyPart);

    if (attachments != null && !attachments.isEmpty()) {
        LOGGER.debug("Use attachments: " + attachments.size());
        includeAttachments(mimeMultipart, attachments);
    }

    msg.setContent(mimeMultipart);

    return msg;
}

From source file:com.aurel.track.util.emailHandling.MailBuilder.java

/**
 * Prepares a plain MimeMessage: the MimeMessage.RecipientType.TO is not yet set
 * @return//from w ww .  j  a v a 2s  .co  m
 * @throws Exception
 */
private MimeMessage preparePlainMimeMessage(InternetAddress internetAddressFrom, String subject,
        String plainBody, List<LabelValueBean> attachments) throws Exception {
    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(internetAddressFrom);
    msg.setHeader(XMAILER, xmailer);
    msg.setSubject(subject.trim(), mailEncoding);
    msg.setSentDate(new Date());
    if (attachments == null || attachments.isEmpty()) {
        msg.setText(plainBody, mailEncoding);
    } else {
        MimeMultipart mimeMultipart = new MimeMultipart();

        MimeBodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setText(plainBody, mailEncoding);
        mimeMultipart.addBodyPart(textBodyPart);

        if (attachments != null) {
            includeAttachments(mimeMultipart, attachments);
        }

        msg.setContent(mimeMultipart);
    }
    return msg;
}

From source file:ru.org.linux.util.EmailService.java

public void sendEmail(String nick, String email, boolean isNew) throws MessagingException {
    StringBuilder text = new StringBuilder();

    text.append("?!\n\n");
    if (isNew) {//from   w  w w .j  a  v a  2  s. co m
        text.append(
                "\t?   ? http://www.linux.org.ru/ ?? ?? ?,\n");
    } else {
        text.append(
                "\t?   ? http://www.linux.org.ru/   ?? ?,\n");
    }

    text.append("     ? ? (e-mail).\n\n");
    text.append(
            "  ?    ? ? ?: '");
    text.append(nick);
    text.append("'\n\n");
    text.append(
            "?   ,     - ?  ? ?!\n\n");

    if (isNew) {
        text.append(
                "?     ???    ? http://www.linux.org.ru/,\n");
        text.append(
                "  ?  ? ?   ?    ?.\n\n");
    } else {
        text.append(
                "?      ? ? ? http://www.linux.org.ru/,\n");
        text.append("  ?  ? .\n\n");
    }

    String regcode = User.getActivationCode(configuration.getSecret(), nick, email);

    text.append(
            "?    ?? http://www.linux.org.ru/activate.jsp\n\n");
    text.append(" : ").append(regcode).append("\n\n");
    text.append("  ?!\n");

    Properties props = new Properties();
    props.put("mail.smtp.host", "localhost");
    Session mailSession = Session.getDefaultInstance(props, null);

    MimeMessage emailMessage = new MimeMessage(mailSession);
    emailMessage.setFrom(new InternetAddress("no-reply@linux.org.ru"));

    emailMessage.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(email));
    emailMessage.setSubject("Linux.org.ru registration");
    emailMessage.setSentDate(new Date());
    emailMessage.setText(text.toString(), "UTF-8");

    Transport.send(emailMessage);
}

From source file:com.haulmont.cuba.core.app.EmailSender.java

protected MimeMessage createMimeMessage(SendingMessage sendingMessage) throws MessagingException {
    MimeMessage msg = mailSender.createMimeMessage();
    assignRecipient(sendingMessage, msg);
    msg.setSubject(sendingMessage.getCaption(), StandardCharsets.UTF_8.name());
    msg.setSentDate(timeSource.currentTimestamp());

    assignFromAddress(sendingMessage, msg);
    addHeaders(sendingMessage, msg);/*from   w w w  . j  ava 2  s  .  c om*/

    MimeMultipart content = new MimeMultipart("mixed");
    MimeMultipart textPart = new MimeMultipart("related");

    setMimeMessageContent(sendingMessage, content, textPart);

    for (SendingAttachment attachment : sendingMessage.getAttachments()) {
        MimeBodyPart attachmentPart = createAttachmentPart(attachment);

        if (attachment.getContentId() == null) {
            content.addBodyPart(attachmentPart);
        } else
            textPart.addBodyPart(attachmentPart);
    }

    msg.setContent(content);
    msg.saveChanges();
    return msg;
}

From source file:jease.cms.service.Mails.java

/**
 * Sends an email synchronously./* www. j av a  2 s  . co  m*/
 */
public void send(String sender, String recipients, String subject, String text) throws MessagingException {
    if (properties != null) {
        Session session = Session.getInstance(properties.asProperties(), new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(properties.getUser(), properties.getPassword());
            }
        });
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(sender));
        message.setReplyTo(new InternetAddress[] { new InternetAddress(sender) });
        message.setRecipients(Message.RecipientType.TO, recipients);
        message.setSubject(subject, "utf-8");
        message.setSentDate(new Date());
        message.setHeader("Content-Type", "text/plain; charset=\"utf-8\"");
        message.setHeader("Content-Transfer-Encoding", "quoted-printable");
        message.setText(text, "utf-8");
        Transport.send(message);
    }
}

From source file:org.apache.axis2.transport.mail.EMailSender.java

public void send() throws AxisFault {

    try {//from   w  w  w .j  ava  2  s . c om

        Session session = Session.getInstance(properties, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return passwordAuthentication;
            }
        });
        MimeMessage msg = new MimeMessage(session);

        // Set date - required by rfc2822
        msg.setSentDate(new java.util.Date());

        // Set from - required by rfc2822
        String from = properties.getProperty("mail.smtp.from");
        if (from != null) {
            msg.setFrom(new InternetAddress(from));
        }

        EndpointReference epr = null;
        MailToInfo mailToInfo;

        if (messageContext.getTo() != null && !messageContext.getTo().hasAnonymousAddress()) {
            epr = messageContext.getTo();
        }

        if (epr != null) {
            if (!epr.hasNoneAddress()) {
                mailToInfo = new MailToInfo(epr);
                msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToInfo.getEmailAddress()));

            } else {
                if (from != null) {
                    mailToInfo = new MailToInfo(from);
                    msg.addRecipient(Message.RecipientType.TO,
                            new InternetAddress(mailToInfo.getEmailAddress()));
                } else {
                    String error = EMailSender.class.getName() + "Couldn't countinue due to"
                            + " FROM addressing is NULL";
                    log.error(error);
                    throw new AxisFault(error);
                }
            }
        } else {
            // replyto : from : or reply-path;
            if (from != null) {
                mailToInfo = new MailToInfo(from);
                msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToInfo.getEmailAddress()));
            } else {
                String error = EMailSender.class.getName() + "Couldn't countinue due to"
                        + " FROM addressing is NULL and EPR is NULL";
                log.error(error);
                throw new AxisFault(error);
            }

        }

        msg.setSubject("__ Axis2/Java Mail Message __");

        if (mailToInfo.isxServicePath()) {
            msg.setHeader(Constants.X_SERVICE_PATH, "\"" + mailToInfo.getContentDescription() + "\"");
        }

        if (inReplyTo != null) {
            msg.setHeader(Constants.IN_REPLY_TO, inReplyTo);
        }

        createMailMimeMessage(msg, mailToInfo, format);
        Transport.send(msg);

        log.info("Message being send. [Action = ]" + messageContext.getOptions().getAction());

        sendReceive(messageContext, msg.getMessageID());
    } catch (AddressException e) {
        throw new AxisFault(e.getMessage(), e);
    } catch (MessagingException e) {
        throw new AxisFault(e.getMessage(), e);
    }
}

From source file:org.jenkinsci.plugins.send_mail_builder.SendMailBuilder.java

@Override
public boolean perform(final AbstractBuild<?, ?> build, final Launcher launcher, final BuildListener listener)
        throws IOException, InterruptedException {
    final EnvVars env = build.getEnvironment(listener);
    final String charset = Mailer.descriptor().getCharset();
    final MimeMessage msg = new MimeMessage(Mailer.descriptor().createSession());
    try {//from  w w w. ja  v a 2  s .c om
        msg.setFrom(Mailer.StringToAddress(JenkinsLocationConfiguration.get().getAdminAddress(), charset));
        msg.setContent("", "text/plain");
        msg.setSentDate(new Date());
        String actualReplyTo = env.expand(replyTo);
        if (StringUtils.isBlank(actualReplyTo)) {
            actualReplyTo = Mailer.descriptor().getReplyToAddress();
        }
        if (StringUtils.isNotBlank(actualReplyTo)) {
            msg.setReplyTo(new Address[] { Mailer.StringToAddress(actualReplyTo, charset) });
        }
        msg.setRecipients(RecipientType.TO, toInternetAddresses(listener, env.expand(tos), charset));
        msg.setRecipients(RecipientType.CC, toInternetAddresses(listener, env.expand(ccs), charset));
        msg.setRecipients(RecipientType.BCC, toInternetAddresses(listener, env.expand(bccs), charset));
        msg.setSubject(env.expand(subject), charset);
        msg.setText(env.expand(text), charset);
        Transport.send(msg);
    } catch (final MessagingException e) {
        listener.getLogger().println(Messages.SendMail_FailedToSend());
        e.printStackTrace(listener.error(e.getMessage()));
        return false;
    }
    listener.getLogger().println(Messages.SendMail_SentSuccessfully());
    return true;
}

From source file:org.talend.dataprep.api.service.mail.MailFeedbackSender.java

@Override
public void send(String subject, String body, String sender) {
    try {/*from   w ww .j  a  v a 2 s.  c om*/
        final String recipientList = StringUtils.join((new HashSet<>(Arrays.asList(recipients))).toArray(),
                ',');
        subject = subjectPrefix + subject;
        body = bodyPrefix + "<br/>" + body + "<br/>" + bodySuffix;

        InternetAddress from = new InternetAddress(this.sender);
        InternetAddress replyTo = new InternetAddress(sender);

        Properties p = new Properties();
        p.put("mail.smtp.host", smtpHost);
        p.put("mail.smtp.port", smtpPort);
        p.put("mail.smtp.starttls.enable", "true");
        p.put("mail.smtp.auth", "true");

        MailAuthenticator authenticator = new MailAuthenticator(userName, password);
        Session sendMailSession = Session.getInstance(p, authenticator);

        MimeMessage msg = new MimeMessage(sendMailSession);
        msg.setFrom(from);
        msg.setReplyTo(new Address[] { replyTo });
        msg.addRecipients(Message.RecipientType.TO, recipientList);

        msg.setSubject(subject, "UTF-8");
        msg.setSentDate(new Date());
        Multipart mainPart = new MimeMultipart();
        BodyPart html = new MimeBodyPart();
        html.setContent(body, "text/html; charset=utf-8");
        mainPart.addBodyPart(html);
        msg.setContent(mainPart);
        Transport.send(msg);

        LOGGER.debug("Sending mail:'{}' to '{}'", subject, recipients);
    } catch (Exception e) {
        throw new TDPException(APIErrorCodes.UNABLE_TO_SEND_MAIL, e);
    }
}