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:atd.backend.Register.java

public void sendRegMail(Klant k) throws IOException {
    Properties propMail = new Properties();
    InputStream config = null;/*from  w ww .jav  a  2  s .  co  m*/
    config = new URL(CONFIG_URL).openStream();
    propMail.load(config);

    Properties props = new Properties();
    props.put("mail.smtp.host", propMail.getProperty("host"));
    props.put("mail.smtp.port", 465);
    props.put("mail.smtp.ssl.enable", true);
    Session mailSession = Session.getInstance(props);
    try {
        Logger.getLogger("atd.log").info("Stuurt mail naar: " + k.getEmail());
        MimeMessage msg = new MimeMessage(mailSession);
        msg.setFrom(new InternetAddress(propMail.getProperty("email"), propMail.getProperty("mailName")));
        msg.setRecipients(Message.RecipientType.TO, k.getEmail());
        msg.setSubject("Uw account is aangemaakt");
        msg.setSentDate(Calendar.getInstance().getTime());
        msg.setContent("Beste " + k.getNaam() + ", \n\nUw account " + k.getUsername()
                + " is aangemaakt, U kunt inloggen op de <a href='https://atd.plebian.nl'>ATD website</a>\n",
                "text/html; charset=utf-8");
        // TODO: Heeft OAUTH nodig, maarja we zijn al niet erg netjes met
        // wachtwoorden
        Transport.send(msg, propMail.getProperty("email"), propMail.getProperty("password"));
    } catch (Exception e) {
        Logger.getLogger("atd.log").warning("send failed: " + e.getMessage());
    }
}

From source file:com.autentia.tnt.mail.DefaultMailService.java

public void sendFiles(String to, String subject, String text, Collection<File> attachments)
        throws MessagingException {

    MimeMessage message = new MimeMessage(session);
    Transport t = session.getTransport("smtp");

    message.setFrom(new InternetAddress(configurationUtil.getMailUsername()));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    message.setSubject(subject);/*w ww .ja  va2 s  . c  om*/
    message.setSentDate(new Date());
    if (attachments == null || attachments.size() < 1) {
        message.setText(text);
    } else {
        // create the message part 
        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(text);
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        for (File attachment : attachments) {

            messageBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(attachment);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(attachment.getName());
            multipart.addBodyPart(messageBodyPart);
        }
        message.setContent(multipart);
    }

    t.connect(configurationUtil.getMailUsername(), configurationUtil.getMailPassword());

    t.sendMessage(message, message.getAllRecipients());
    t.close();
}

From source file:ru.org.linux.user.LostPasswordController.java

private void sendEmail(User user, String email, Timestamp resetDate) throws MessagingException {
    Properties props = new Properties();
    props.put("mail.smtp.host", "localhost");
    Session mailSession = Session.getDefaultInstance(props, null);

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

    String resetCode = UserService.getResetCode(configuration.getSecret(), user.getNick(), email, resetDate);

    msg.addRecipient(RecipientType.TO, new InternetAddress(email));
    msg.setSubject("Your password @linux.org.ru");
    msg.setSentDate(new Date());
    msg.setText("?!\n\n"
            + "? ??  ?   ?? http://www.linux.org.ru/reset-password\n\n"
            + "  " + user.getNick() + ",  ?: " + resetCode + "\n\n"
            + "!");

    Transport.send(msg);/*w w  w . j a  va 2 s  . c  o  m*/
}

From source file:org.snopoke.util.Emailer.java

/**
 * Create the MimeMessage and set the to/from/subject
 * /*from w ww . ja  va2s . c o m*/
 * @return MimeMessaeg
 * @throws MessagingException
 */
private MimeMessage getMessasge() throws MessagingException {
    MimeMessage message = new MimeMessage(getSession());
    message.setSentDate(new Date());

    for (Address toAddress : to) {
        message.addRecipient(RecipientType.TO, toAddress.getInternetAddress());
    }

    for (Address toAddress : cc) {
        message.addRecipient(RecipientType.CC, toAddress.getInternetAddress());
    }

    for (Address toAddress : bcc) {
        message.addRecipient(RecipientType.BCC, toAddress.getInternetAddress());
    }

    message.setFrom(from.getInternetAddress());

    if (subject != null && !subject.isEmpty())
        message.setSubject(subject, "UTF-8");
    return message;
}

From source file:net.duckling.ddl.service.mail.impl.MailServiceImpl.java

public void sendMail(Mail mail) {
    LOG.debug("sendEmail() to: " + mail.getRecipient());
    try {/*www .  j  a v a 2s .com*/
        Session session = Session.getInstance(m_bag.m_mailProperties, m_bag.m_authenticator);
        session.setDebug(false);
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(m_bag.m_fromAddress);
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mail.getRecipient()));
        msg.setSubject(mail.getSubject());
        msg.setSentDate(new Date());

        Multipart mp = new MimeMultipart();

        MimeBodyPart txtmbp = new MimeBodyPart();
        txtmbp.setContent(mail.getMessage(), EMAIL_CONTENT_TYPE);
        mp.addBodyPart(txtmbp);

        List<String> attachments = mail.getAttachments();
        for (Iterator<String> it = attachments.iterator(); it.hasNext();) {
            MimeBodyPart mbp = new MimeBodyPart();
            String filename = it.next();
            FileDataSource fds = new FileDataSource(filename);
            mbp.setDataHandler(new DataHandler(fds));
            mbp.setFileName(MimeUtility.encodeText(fds.getName()));
            mp.addBodyPart(mbp);
        }

        msg.setContent(mp);

        if ((m_bag.m_fromAddress != null) && (m_bag.m_fromAddress.getAddress() != null)
                && (m_bag.m_fromAddress.getAddress().indexOf("@") != -1)) {
            cheat(msg,
                    m_bag.m_fromAddress.getAddress().substring(m_bag.m_fromAddress.getAddress().indexOf("@")));
        }

        Transport.send(msg);

        LOG.info("Successfully send the mail to " + mail.getRecipient());

    } catch (Throwable e) {

        LOG.error("Exception occured while trying to send notification to: " + mail.getRecipient(), e);
        LOG.debug("Details:", e);
    }
}

From source file:com.brienwheeler.svc.email.impl.EmailService.java

/**
 * This is a private method (rather than having the public template method
 * call the public non-template method) to prevent inaccurate MonitoredWork
 * operation counts./*from w  w  w. j  a v  a 2 s  .com*/
 * 
 * @param recipient
 * @param subject
 * @param body
 */
private void doSendEmail(EmailAddress recipient, String subject, String body) {
    ValidationUtils.assertNotNull(recipient, "recipient cannot be null");
    subject = ValidationUtils.assertNotEmpty(subject, "subject cannot be empty");
    body = ValidationUtils.assertNotEmpty(body, "body cannot be empty");

    try {
        MimeMessage message = new MimeMessage(mailSession);
        message.setFrom(new InternetAddress(fromAddress.getAddress()));
        message.setRecipients(Message.RecipientType.TO, recipient.getAddress());
        message.setSubject(subject);
        message.setSentDate(new Date());
        message.setText(body);
        Transport.send(message);
        log.info("sent email to " + recipient.getAddress() + " (" + subject + ")");
    } catch (MessagingException e) {
        throw new ServiceOperationException(e);
    }
}

From source file:com.autentia.tnt.mail.DefaultMailService.java

public void sendOutputStreams(String to, String subject, String text, Map<InputStream, String> attachments)
        throws MessagingException {
    Transport t = null;/*from  w ww . j  av  a 2s . c o m*/

    try {
        MimeMessage message = new MimeMessage(session);

        t = session.getTransport("smtp");

        message.setFrom(new InternetAddress(configurationUtil.getMailUsername()));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject);
        message.setSentDate(new Date());
        if (attachments == null || attachments.size() < 1) {
            message.setText(text);
        } else {
            // create the message part 
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(text);
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);
            try {
                for (InputStream attachment : attachments.keySet()) {
                    messageBodyPart = new MimeBodyPart();
                    DataSource source = new ByteArrayDataSource(attachment, "application/octet-stream");

                    messageBodyPart.setDataHandler(new DataHandler(source));
                    messageBodyPart.setFileName(attachments.get(attachment)); //NOSONAR 
                    multipart.addBodyPart(messageBodyPart); //Se emplea keyset y no valueset porque se emplea tanto la key como el val
                }
            } catch (IOException e) {
                throw new MessagingException("cannot add an attachment to mail", e);
            }
            message.setContent(multipart);
        }

        t.connect(configurationUtil.getMailUsername(), configurationUtil.getMailPassword());

        t.sendMessage(message, message.getAllRecipients());
    } finally {
        if (t != null) {
            t.close();
        }
    }

}

From source file:org.mule.transport.email.transformers.StringToEmailMessage.java

@Override
public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException {
    String endpointAddress = endpoint.getEndpointURI().getAddress();
    SmtpConnector connector = (SmtpConnector) endpoint.getConnector();
    String to = lookupProperty(message, MailProperties.TO_ADDRESSES_PROPERTY, endpointAddress);
    String cc = lookupProperty(message, MailProperties.CC_ADDRESSES_PROPERTY, connector.getCcAddresses());
    String bcc = lookupProperty(message, MailProperties.BCC_ADDRESSES_PROPERTY, connector.getBccAddresses());
    String from = lookupProperty(message, MailProperties.FROM_ADDRESS_PROPERTY, connector.getFromAddress());
    String replyTo = lookupProperty(message, MailProperties.REPLY_TO_ADDRESSES_PROPERTY,
            connector.getReplyToAddresses());
    String subject = lookupProperty(message, MailProperties.SUBJECT_PROPERTY, connector.getSubject());
    String contentType = lookupProperty(message, MailProperties.CONTENT_TYPE_PROPERTY,
            connector.getContentType());

    Properties headers = new Properties();
    Properties customHeaders = connector.getCustomHeaders();

    if (customHeaders != null && !customHeaders.isEmpty()) {
        headers.putAll(customHeaders);/*from  w ww. j av a 2s. co m*/
    }

    Properties otherHeaders = message.getOutboundProperty(MailProperties.CUSTOM_HEADERS_MAP_PROPERTY);
    if (otherHeaders != null && !otherHeaders.isEmpty()) {
        //TODO Whats going on here?
        //                final MuleContext mc = context.getMuleContext();
        //                for (Iterator iterator = message.getPropertyNames().iterator(); iterator.hasNext();)
        //                {
        //                    String propertyKey = (String) iterator.next();
        //                    mc.getRegistry().registerObject(propertyKey, message.getProperty(propertyKey), mc);
        //                }
        headers.putAll(templateParser.parse(new TemplateParser.TemplateCallback() {
            public Object match(String token) {
                return muleContext.getRegistry().lookupObject(token);
            }
        }, otherHeaders));

    }

    if (logger.isDebugEnabled()) {
        StringBuffer buf = new StringBuffer();
        buf.append("Constructing email using:\n");
        buf.append("To: ").append(to);
        buf.append(", From: ").append(from);
        buf.append(", CC: ").append(cc);
        buf.append(", BCC: ").append(bcc);
        buf.append(", Subject: ").append(subject);
        buf.append(", ReplyTo: ").append(replyTo);
        buf.append(", Content type: ").append(contentType);
        buf.append(", Payload type: ").append(message.getPayload().getClass().getName());
        buf.append(", Custom Headers: ").append(MapUtils.toString(headers, false));
        logger.debug(buf.toString());
    }

    try {
        MimeMessage email = new MimeMessage(
                ((SmtpConnector) endpoint.getConnector()).getSessionDetails(endpoint).getSession());

        email.setRecipients(Message.RecipientType.TO, MailUtils.stringToInternetAddresses(to));

        // sent date
        email.setSentDate(Calendar.getInstance().getTime());

        if (StringUtils.isNotBlank(from)) {
            email.setFrom(MailUtils.stringToInternetAddresses(from)[0]);
        }

        if (StringUtils.isNotBlank(cc)) {
            email.setRecipients(Message.RecipientType.CC, MailUtils.stringToInternetAddresses(cc));
        }

        if (StringUtils.isNotBlank(bcc)) {
            email.setRecipients(Message.RecipientType.BCC, MailUtils.stringToInternetAddresses(bcc));
        }

        if (StringUtils.isNotBlank(replyTo)) {
            email.setReplyTo(MailUtils.stringToInternetAddresses(replyTo));
        }

        email.setSubject(subject, outputEncoding);

        for (Iterator iterator = headers.entrySet().iterator(); iterator.hasNext();) {
            Map.Entry entry = (Map.Entry) iterator.next();
            email.setHeader(entry.getKey().toString(), entry.getValue().toString());
        }

        setContent(message.getPayload(), email, contentType, message);

        return email;
    } catch (Exception e) {
        throw new TransformerException(this, e);
    }
}

From source file:ru.org.linux.exception.ExceptionResolver.java

/**
 * ? E-mail ?.//from w  w w.  j  a  v a  2  s .  co m
 *
 * @param request    ?  web-
 * @param exception ?
 * @return , ? ??? ? ?
 */
private String sendEmailToAdmin(HttpServletRequest request, Exception exception) {
    InternetAddress mail;
    String adminEmailAddress = configuration.getAdminEmailAddress();

    try {
        mail = new InternetAddress(adminEmailAddress, true);
    } catch (AddressException e) {
        return EMAIL_NOT_SENT + " ? e-mail ?: " + adminEmailAddress;
    }
    StringBuilder text = new StringBuilder();

    if (exception.getMessage() == null) {
        text.append(exception.getClass().getName());
    } else {
        text.append(exception.getMessage());
    }
    text.append("\n\n");

    Template tmpl = Template.getTemplate(request);
    //    text.append("Main URL: ").append(tmpl.getMainUrl()).append(request.getAttribute("javax.servlet.error.request_uri"));
    String mainUrl = "<unknown>";

    mainUrl = configuration.getMainUrl();

    text.append("Main URL: ").append(mainUrl).append(request.getServletPath());

    if (request.getQueryString() != null) {
        text.append('?').append(request.getQueryString()).append('\n');
    }
    text.append('\n');

    text.append("IP: " + request.getRemoteAddr() + '\n');

    text.append(" Headers: ");
    Enumeration enu = request.getHeaderNames();
    while (enu.hasMoreElements()) {
        String paramName = (String) enu.nextElement();
        text.append("\n         ").append(paramName).append(": ").append(request.getHeader(paramName));
    }
    text.append("\n\n");

    StringWriter exceptionStackTrace = new StringWriter();
    exception.printStackTrace(new PrintWriter(exceptionStackTrace));
    text.append(exceptionStackTrace.toString());

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

    MimeMessage emailMessage = new MimeMessage(mailSession);
    try {
        emailMessage.setFrom(new InternetAddress("no-reply@linux.org.ru"));
        emailMessage.addRecipient(Message.RecipientType.TO, mail);
        emailMessage.setSubject("Linux.org.ru: " + exception.getClass());
        emailMessage.setSentDate(new Date());
        emailMessage.setText(text.toString(), "UTF-8");
    } catch (Exception e) {
        logger.error("An error occured while creating e-mail!", e);
        return EMAIL_NOT_SENT;
    }
    try {
        Transport.send(emailMessage);
        return EMAIL_SENT;
    } catch (Exception e) {
        return EMAIL_NOT_SENT;
    }
}

From source file:org.silverpeas.core.mail.engine.SmtpMailSender.java

@Override
public void send(final MailToSend mail) {
    SmtpConfiguration smtpConfiguration = SmtpConfiguration.fromDefaultSettings();

    MailAddress fromMailAddress = mail.getFrom();
    Session session = getMailSession(smtpConfiguration);
    try {//w w  w . j  a  v a 2 s .  c  om
        InternetAddress fromAddress = fromMailAddress.getAuthorizedInternetAddress();
        InternetAddress replyToAddress = null;
        List<InternetAddress[]> toAddresses = new ArrayList<>();

        // Parsing destination address for compliance with RFC822.
        final Collection<ReceiverMailAddressSet> addressBatches = mail.getTo().getBatchedReceiversList();
        for (ReceiverMailAddressSet addressBatch : addressBatches) {
            try {
                toAddresses.add(InternetAddress.parse(addressBatch.getEmailsSeparatedByComma(), false));
            } catch (AddressException e) {
                SilverTrace.warn("mail", "MailSender.send()", "root.MSG_GEN_PARAM_VALUE",
                        "From = " + fromMailAddress + ", To = " + addressBatch.getEmailsSeparatedByComma(), e);
            }
        }
        try {
            if (mail.isReplyToRequired()) {
                replyToAddress = new InternetAddress(fromMailAddress.getEmail(), false);
                if (StringUtil.isDefined(fromMailAddress.getName())) {
                    replyToAddress.setPersonal(fromMailAddress.getName(), Charsets.UTF_8.name());
                }
            }
        } catch (AddressException e) {
            SilverTrace.warn("mail", "MailSender.send()", "root.MSG_GEN_PARAM_VALUE",
                    "ReplyTo = " + fromMailAddress + " is malformed.", e);
        }
        MimeMessage email = new MimeMessage(session);
        email.setFrom(fromAddress);
        if (replyToAddress != null) {
            email.setReplyTo(new InternetAddress[] { replyToAddress });
        }
        email.setHeader("Precedence", "list");
        email.setHeader("List-ID", fromAddress.getAddress());
        email.setSentDate(new Date());
        email.setSubject(mail.getSubject(), CharEncoding.UTF_8);
        mail.getContent().applyOn(email);

        // Sending.
        performSend(mail, smtpConfiguration, session, email, toAddresses);

    } catch (MessagingException | UnsupportedEncodingException e) {
        SilverLogger.getLogger(this).error(e.getMessage(), e);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}