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.beanfuse.notification.mail.AbstractMailNotifier.java

public void sendMessage(Message msg) throws NotificationException {
    // contruct a MailMessage
    MailMessage mailConext = null;//from   ww w .ja  va 2s . co  m
    if (msg instanceof MailMessage) {
        mailConext = (MailMessage) msg;
    } else {
        mailConext = new MailMessage();
        mailConext.setSubject(msg.getSubject());
        mailConext.setText(msg.getText());
        mailConext.setProperties(msg.getProperties());
        String[] to = new String[msg.getRecipients().size()];
        msg.getRecipients().toArray(to);
        mailConext.setTo(to);
    }

    MimeMessage mimeMsg = javaMailSender.createMimeMessage();
    try {
        mimeMsg.setSentDate(new Date());
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMsg);
        messageHelper.setText(buildText(mailConext), Message.HTML.equals(mailConext.getContentType()));
        String subject = buildSubject(mailConext);
        messageHelper.setSubject(subject);
        messageHelper.setFrom(fromMailbox, fromName);
        addRecipient(mimeMsg, javax.mail.Message.RecipientType.TO, mailConext.getTo());
        addRecipient(mimeMsg, javax.mail.Message.RecipientType.CC, mailConext.getCc());
        addRecipient(mimeMsg, javax.mail.Message.RecipientType.BCC, mailConext.getBcc());
        beforeSend(mailConext, mimeMsg);
        if (mimeMsg.getAllRecipients() != null && ((Address[]) mimeMsg.getAllRecipients()).length > 0) {
            javaMailSender.send(mimeMsg);
            logger.info("mail sended from {} to {} with subject {}",
                    new Object[] { fromMailbox, mailConext.getRecipients(), subject });
        }
    } catch (AddressException ex) {
        throw new NotificationException("Exception while sending message.", ex);
    } catch (MessagingException ex) {
        throw new NotificationException("Exception while sending message.", ex);
    } catch (UnsupportedEncodingException ex) {
        throw new NotificationException("Exception while sending message.", ex);
    }
    afterSend(mailConext, mimeMsg);
}

From source file:easyproject.service.Mail.java

public void sendMail() {
    Properties props = new Properties();

    props.put("mail.debug", "true");
    props.put("mail.smtp.auth", true);
    props.put("mail.smtp.starttls.enable", true);
    props.put("mail.smtp.host", servidorSMTP);
    props.put("mail.smtp.port", puerto);

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

    try {/* w ww  . j  a  v  a  2 s.  c om*/
        MimeMessage message = new MimeMessage(session);

        message.addRecipient(Message.RecipientType.TO, new InternetAddress(destino));
        message.setSubject(asunto);
        message.setSentDate(new Date());
        message.setContent(mensaje, "text/html; charset=utf-8");

        Transport tr = session.getTransport("smtp");
        tr.connect(servidorSMTP, usuario, password);
        message.saveChanges();
        tr.sendMessage(message, message.getAllRecipients());
        tr.close();

    } catch (MessagingException e) {
        e.printStackTrace();
    }
}

From source file:org.beangle.notification.notifiers.mail.AbstractMailNotifier.java

public void deliver(T mailMsg) throws NotificationException {
    MimeMessage mimeMsg = mailSender.createMimeMessage();
    try {//from  w w w  .ja  v  a2 s  . c  o m
        if (null == mailMsg.getSendAt()) {
            mimeMsg.setSentDate(new Date());
        } else {
            mimeMsg.setSentDate(mailMsg.getSendAt());
        }
        MimeMessageHelper messageHelper = null;
        String encoding = StringUtils.substringAfter(mailMsg.getContentType(), "charset=");
        if (StringUtils.isEmpty(encoding)) {
            messageHelper = new MimeMessageHelper(mimeMsg);
        } else {
            messageHelper = new MimeMessageHelper(mimeMsg, encoding);
        }
        messageHelper.setText(buildText(mailMsg), StringUtils.contains(mailMsg.getContentType(), "html"));
        String subject = buildSubject(mailMsg);
        messageHelper.setSubject(subject);
        int recipients = addRecipient(mimeMsg, mailMsg);
        beforeSend(mailMsg, mimeMsg);
        if (recipients > 0) {
            mailSender.send(mimeMsg);
            if (logger.isDebugEnabled()) {
                logger.debug("mail sended from {} to {} with subject {}",
                        new Object[] { from, mailMsg.getRecipients(), subject });
            }
        } else {
            logger.warn("{} without any recipients ,sending aborted!", subject);
        }
    } catch (AddressException ex) {
        throw new NotificationException("Exception while sending message.", ex);
    } catch (MessagingException ex) {
        throw new NotificationException("Exception while sending message.", ex);
    }
    afterSend(mailMsg, mimeMsg);
}

From source file:easyproject.utils.SendMail.java

@Override
public void run() {

    Properties props = new Properties();

    props.put("mail.debug", "true");
    props.put("mail.smtp.auth", true);
    props.put("mail.smtp.starttls.enable", true);
    props.put("mail.smtp.host", servidorSMTP);
    props.put("mail.smtp.port", puerto);

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

    try {/*  w w  w .  j a  v a  2  s. co m*/
        MimeMessage message1 = new MimeMessage(session);

        message1.addRecipient(Message.RecipientType.TO, new InternetAddress(destino));
        message1.setSubject(asunto);
        message1.setSentDate(new Date());
        message1.setContent(mensaje, "text/html; charset=utf-8");

        Transport tr = session.getTransport("smtp");
        tr.connect(servidorSMTP, usuario, password);
        message1.saveChanges();
        tr.sendMessage(message1, message1.getAllRecipients());
        tr.close();

    } catch (MessagingException e) {
        e.printStackTrace();
    }

}

From source file:com.mycompany.login.mb.EmailBean.java

public void envia() throws AddressException, MessagingException {
    Session session = Session.getInstance(this.propriedades, this.authentication);
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress("anderson.freitas@lifemed.com.br"));
    message.setRecipients(Message.RecipientType.TO, "anderson.freitas@lifemed.com.br");
    message.setSentDate(new Date());
    message.setSubject("Teste envio jsf");
    message.setContent("Sua solicitao foi aprovada: OS n" + this.os, "text/plain");

    Transport.send(message);//www .  j  a va2  s.  c  o m

}

From source file:io.kamax.mxisd.threepid.connector.email.EmailSmtpConnector.java

@Override
public void send(String senderAddress, String senderName, String recipient, String content) {
    if (StringUtils.isBlank(senderAddress)) {
        throw new FeatureNotAvailable("3PID Email identity: sender address is empty - "
                + "You must set a value for notifications to work");
    }/*from w  w w . ja va 2  s  .c o m*/

    if (StringUtils.isBlank(content)) {
        throw new InternalServerError("Notification content is empty");
    }

    try {
        InternetAddress sender = new InternetAddress(senderAddress, senderName);
        MimeMessage msg = new MimeMessage(session, IOUtils.toInputStream(content, StandardCharsets.UTF_8));
        msg.setHeader("X-Mailer", "mxisd"); // FIXME set version
        msg.setSentDate(new Date());
        msg.setFrom(sender);
        msg.setRecipients(Message.RecipientType.TO, recipient);
        msg.saveChanges();

        log.info("Sending invite to {} via SMTP using {}:{}", recipient, cfg.getHost(), cfg.getPort());
        SMTPTransport transport = (SMTPTransport) session.getTransport("smtp");
        transport.setStartTLS(cfg.getTls() > 0);
        transport.setRequireStartTLS(cfg.getTls() > 1);

        log.info("Connecting to {}:{}", cfg.getHost(), cfg.getPort());
        transport.connect(cfg.getHost(), cfg.getPort(), cfg.getLogin(), cfg.getPassword());
        try {
            transport.sendMessage(msg, InternetAddress.parse(recipient));
            log.info("Invite to {} was sent", recipient);
        } finally {
            transport.close();
        }
    } catch (UnsupportedEncodingException | MessagingException e) {
        throw new RuntimeException("Unable to send e-mail invite to " + recipient, e);
    }
}

From source file:com.medsavant.mailer.Mail.java

public synchronized static boolean sendEmail(String to, String subject, String text, File attachment) {
    try {//from  w  w  w. j  ava 2 s  .c  o  m

        if (src == null || pw == null || host == null || port == -1) {
            return false;
        }

        if (to.isEmpty()) {
            return false;
        }

        LOG.info("Sending email to " + to + " with subject " + subject);

        // create some properties and get the default Session
        Properties props = new Properties();
        props.put("mail.smtp.user", src);
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.starttls.enable", starttls);
        props.put("mail.smtp.auth", auth);
        props.put("mail.smtp.socketFactory.port", port);
        props.put("mail.smtp.socketFactory.class", socketFactoryClass);
        props.put("mail.smtp.socketFactory.fallback", fallback);
        Session session = Session.getInstance(props, null);
        // create a message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(src, srcName));
        InternetAddress[] address = InternetAddress.parse(to);
        msg.setRecipients(Message.RecipientType.BCC, address);
        msg.setSubject(subject);
        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();

        mbp1.setContent(text, "text/html");

        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);

        if (attachment != null) {
            // create the second message part
            MimeBodyPart mbp2 = new MimeBodyPart();
            // attach the file to the message
            FileDataSource fds = new FileDataSource(attachment);
            mbp2.setDataHandler(new DataHandler(fds));
            mbp2.setFileName(fds.getName());
            mp.addBodyPart(mbp2);
        }

        // add the Multipart to the message
        msg.setContent(mp);
        // set the Date: header
        msg.setSentDate(new Date());
        // send the message
        Transport transport = session.getTransport("smtp");
        transport.connect(host, src, pw);
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();

        LOG.info("Mail sent");

        return true;

    } catch (Exception ex) {
        ex.printStackTrace();
        LOG.error(ex);
        return false;
    }

}

From source file:org.eurekastreams.server.service.actions.strategies.EmailerFactory.java

/**
 * Creates a "blank" email message, ready for the application to set the content (subject, body, etc.).
 *
 * @return An email message.//from  w  w w.j  a v  a  2  s  . co m
 * @throws MessagingException
 *             Thrown if there are problems creating the message.
 */
public MimeMessage createMessage() throws MessagingException {
    Properties mailProps = new Properties();
    mailProps.put("mail.transport.protocol", mailTransportProtocol);
    for (Map.Entry<String, String> cfg : transportConfiguration.entrySet()) {
        mailProps.put(cfg.getKey(), cfg.getValue());
    }
    Session mailSession = Session.getInstance(mailProps, null);

    MimeMessage msg = new MimeMessage(mailSession);
    msg.setContent(new MimeMultipart("alternative"));
    msg.setSentDate(new Date());
    msg.setFrom(new InternetAddress(defaultFromAddress));

    return msg;
}

From source file:com.unilever.audit.services2.ForgetPassword.java

@GET
@Path("Email/{email}")
@Produces("application/json")
public String LoginIn(@PathParam("email") String email) throws IOException {
    boolean status = true;
    String error = null;//ww  w . j a va2 s  .c om
    JSONObject result = new JSONObject();

    Map<String, Object> hm = new HashMap<String, Object>();
    hm.put("email", email);
    Merchandisers merchidisers = (Merchandisers) merchandisersFacadeREST
            .findOneByQuery("Merchandisers.findByEmail", hm);
    if (merchidisers == null) {
        status = false;
        error = "invalid email";
    } else {
        Properties props = new Properties();
        final String from = "";
        final String password = "";
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.user", from);
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.password", password);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");

        Session session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, password);
            }
        });
        session.setDebug(true);
        try {
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom();
            msg.setRecipients(Message.RecipientType.TO, email);
            msg.setSubject("Unilever Confirmation");
            msg.setSentDate(new Date());
            msg.setText("");
            Transport.send(msg);
        } catch (MessagingException ex) {
            //  status = false;
            //  error="Error Sending Email";
            ex.printStackTrace();
        }
    }
    result.put("status", status);
    result.put("error", error);
    System.out.println("----------------" + result.toString());
    return result.toString();
}

From source file:be.fedict.eid.dss.model.bean.TaskMDB.java

private void sendMail(String mailTo, String subject, String messageBody, String attachmentMimetype,
        byte[] attachment) {
    LOG.debug("sending email to " + mailTo + " with subject \"" + subject + "\"");
    String smtpServer = this.configuration.getValue(ConfigProperty.SMTP_SERVER, String.class);
    if (null == smtpServer || smtpServer.trim().isEmpty()) {
        LOG.warn("no SMTP server configured");
        return;/*from w w  w.jav  a 2  s  .  c o  m*/
    }
    String mailFrom = this.configuration.getValue(ConfigProperty.MAIL_FROM, String.class);
    if (null == mailFrom || mailFrom.trim().isEmpty()) {
        LOG.warn("no mail from address configured");
        return;
    }
    LOG.debug("mail from: " + mailFrom);

    Properties props = new Properties();
    props.put("mail.smtp.host", smtpServer);
    props.put("mail.from", mailFrom);

    String mailPrefix = this.configuration.getValue(ConfigProperty.MAIL_PREFIX, String.class);
    if (null != mailPrefix && false == mailPrefix.trim().isEmpty()) {
        subject = "[" + mailPrefix.trim() + "] " + subject;
    }

    Session session = Session.getInstance(props, null);
    try {
        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setFrom();
        mimeMessage.setRecipients(RecipientType.TO, mailTo);
        mimeMessage.setSubject(subject);
        mimeMessage.setSentDate(new Date());

        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        mimeBodyPart.setText(messageBody);

        Multipart multipart = new MimeMultipart();
        // first part is body
        multipart.addBodyPart(mimeBodyPart);

        // second part is attachment
        if (null != attachment) {
            MimeBodyPart attachmentMimeBodyPart = new MimeBodyPart();
            DataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimetype);
            attachmentMimeBodyPart.setDataHandler(new DataHandler(dataSource));
            multipart.addBodyPart(attachmentMimeBodyPart);
        }

        mimeMessage.setContent(multipart);
        Transport.send(mimeMessage);
    } catch (MessagingException e) {
        throw new RuntimeException("send failed, exception: " + e.getMessage(), e);
    }
}