Example usage for javax.mail.internet MimeMessage MimeMessage

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

Introduction

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

Prototype

public MimeMessage(MimeMessage source) throws MessagingException 

Source Link

Document

Constructs a new MimeMessage with content initialized from the source MimeMessage.

Usage

From source file:com.smartitengineering.emailq.service.impl.EmailServiceImpl.java

protected void sendEmail(Email email, List<Email> successfulEmails) {
    try {/*w w  w .  java2  s.  c  o m*/
        if (logger.isDebugEnabled()) {
            logger.debug("Attempting to send " + email.getId() + " " + email.getSubject());
            if (email.getTo() != null) {
                logger.debug("To: " + Arrays.toString(email.getTo().toArray()));
            } else {
                logger.debug("To is NULL");
            }
            if (email.getTo() != null) {
                logger.debug("CC: " + Arrays.toString(email.getCc().toArray()));
            } else {
                logger.debug("CC is NULL");
            }
            if (email.getTo() != null) {
                logger.debug("BCC: " + Arrays.toString(email.getBcc().toArray()));
            } else {
                logger.debug("BCC is NULL");
            }
            if (email.getTo() != null) {
                logger.debug("FROM: " + email.getFrom());
            } else {
                logger.debug("FROM is NULL");
            }
            if (email.getAttachments() != null) {
                logger.debug("Attachments: " + Arrays.toString(email.getAttachments().toArray()));
                for (Attachments attachment : email.getAttachments()) {
                    logger.debug("Attachment: " + attachment.getName());
                }
            } else {
                logger.debug("No attachments");
            }
        }
        //Send email
        if (StringUtils.isBlank(email.getSubject()) || StringUtils.isBlank(email.getFrom())) {
            logger.warn(new StringBuilder("Invalid email without either from or a subject, thus ignoring it ")
                    .append(email.getId()).toString());
            return;
        }
        MimeMessage message = new MimeMessage(session);
        message.setSubject(email.getSubject());
        message.setFrom(new InternetAddress(email.getFrom()));
        addRecipients(message, Message.RecipientType.TO, email.getTo());
        addRecipients(message, Message.RecipientType.CC, email.getCc());
        addRecipients(message, Message.RecipientType.BCC, email.getBcc());
        if (email.getMessage() != null && StringUtils.isNotBlank(email.getMessage().getMsgBody())
                && email.getMessage().getMsgType().equals(MsgType.PLAIN)
                && (email.getAttachments() == null || email.getAttachments().isEmpty())) {
            message.setText(email.getMessage().getMsgBody());
        } else {
            Multipart multipart = new MimeMultipart();
            if (email.getMessage() != null && StringUtils.isNotBlank(email.getMessage().getMsgBody())) {
                MimeBodyPart bodyPart = new MimeBodyPart();
                switch (email.getMessage().getMsgType()) {
                case HTML:
                    bodyPart.setContent(email.getMessage().getMsgBody(), "html");
                    break;
                case PLAIN:
                default:
                    bodyPart.setText(email.getMessage().getMsgBody());
                }
                multipart.addBodyPart(bodyPart);
            }
            if (email.getAttachments() != null && !email.getAttachments().isEmpty()) {
                for (Attachments attachment : email.getAttachments()) {
                    addAttachment(multipart, attachment);
                }
            }
            message.setContent(multipart);
        }
        Transport.send(message);
        if (logger.isDebugEnabled()) {
            logger.debug("Sent " + email.getId());
        }
        //Update status
        email.setMailStatus(Email.MailStatus.SENT);
        successfulEmails.add(email);
        if (logger.isDebugEnabled()) {
            logger.debug("Set new mail status and add to successful queue " + email.getSubject());
        }
    } catch (Exception ex) {
        logger.warn(
                new StringBuilder("Error sending email with subject ").append(email.getSubject()).toString(),
                ex);
    }
}

From source file:at.gv.egovernment.moa.id.configuration.helper.MailHelper.java

private static void sendMail(ConfigurationProvider config, String subject, String recipient, String content)
        throws ConfigurationException {
    try {/*w  w  w  .java2s.  c  o m*/
        log.debug("Sending mail.");
        MiscUtil.assertNotNull(subject, "subject");
        MiscUtil.assertNotNull(recipient, "recipient");
        MiscUtil.assertNotNull(content, "content");

        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.host", config.getSMTPMailHost());
        log.trace("Mail host: " + config.getSMTPMailHost());
        if (config.getSMTPMailPort() != null) {
            log.trace("Mail port: " + config.getSMTPMailPort());
            props.setProperty("mail.port", config.getSMTPMailPort());
        }
        if (config.getSMTPMailUsername() != null) {
            log.trace("Mail user: " + config.getSMTPMailUsername());
            props.setProperty("mail.user", config.getSMTPMailUsername());
        }
        if (config.getSMTPMailPassword() != null) {
            log.trace("Mail password: " + config.getSMTPMailPassword());
            props.setProperty("mail.password", config.getSMTPMailPassword());
        }

        Session mailSession = Session.getDefaultInstance(props, null);
        Transport transport = mailSession.getTransport();

        MimeMessage message = new MimeMessage(mailSession);
        message.setSubject(subject);
        log.trace("Mail from: " + config.getMailFromName() + "/" + config.getMailFromAddress());
        message.setFrom(new InternetAddress(config.getMailFromAddress(), config.getMailFromName()));
        log.trace("Recipient: " + recipient);
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));

        log.trace("Creating multipart content of mail.");
        MimeMultipart multipart = new MimeMultipart("related");

        log.trace("Adding first part (html)");
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(content, "text/html; charset=ISO-8859-15");
        multipart.addBodyPart(messageBodyPart);

        //         log.trace("Adding mail images");
        //         messageBodyPart = new MimeBodyPart();
        //         for (Image image : images) {
        //            messageBodyPart.setDataHandler(new DataHandler(image));
        //            messageBodyPart.setHeader("Content-ID", "<" + image.getContentId() + ">");
        //            multipart.addBodyPart(messageBodyPart);
        //         }

        message.setContent(multipart);
        transport.connect();
        log.trace("Sending mail message.");
        transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
        log.trace("Successfully sent.");
        transport.close();

    } catch (MessagingException e) {
        throw new ConfigurationException(e);

    } catch (UnsupportedEncodingException e) {
        throw new ConfigurationException(e);

    }
}

From source file:com.szmslab.quickjavamail.send.MailSender.java

/**
 * ????//  w  w w  .  j ava 2 s . co  m
 *
 * @throws UnsupportedEncodingException
 * @throws MessagingException
 */
public void execute() throws UnsupportedEncodingException, MessagingException {
    final Session session = useDefaultSession
            ? Session.getDefaultInstance(properties.getProperties(), properties.getAuthenticator())
            : Session.getInstance(properties.getProperties(), properties.getAuthenticator());
    session.setDebug(isDebug);

    final MimeMessage message = new MimeMessage(session);

    message.setFrom(fromAddress.toInternetAddress(charset));
    message.setReplyTo(toInternetAddresses(replyToAddressList));
    message.addRecipients(Message.RecipientType.TO, toInternetAddresses(toAddressList));
    message.addRecipients(Message.RecipientType.CC, toInternetAddresses(ccAddressList));
    message.addRecipients(Message.RecipientType.BCC, toInternetAddresses(bccAddressList));
    message.setSubject(subject, charset);

    setContent(message);

    message.setSentDate(new Date());

    Transport.send(message);
}

From source file:davmail.smtp.TestSmtp.java

public void testSendHtmlMessage() throws IOException, MessagingException, InterruptedException {
    String body = "Test html message <font color=\"#ff0000\">red</font>";
    MimeMessage mimeMessage = new MimeMessage((Session) null);
    mimeMessage.addHeader("To", Settings.getProperty("davmail.to"));
    mimeMessage.setSubject("Test html message");
    mimeMessage.setContent(body, "text/html");
    sendAndCheckMessage(mimeMessage);//from   www  .jav a2s.c om
}

From source file:jp.co.acroquest.endosnipe.collector.notification.smtp.SMTPSender.java

/**
 * ??/*from w  ww . ja va  2s.c  om*/
 * 
 * @param config javelin.properties???
 * @param entry ??
 * @return ???
 * @throws MessagingException ??????
 */
protected MimeMessage createMailMessage(final DataCollectorConfig config, final AlarmEntry entry)
        throws MessagingException {
    // JavaMail???
    Properties props = System.getProperties();
    String smtpServer = this.config_.getSmtpServer();
    if (smtpServer == null || smtpServer.length() == 0) {
        LOGGER.log(LogMessageCodes.SMTP_SERVER_NOT_SPECIFIED);
        String detailMessageKey = "collector.notification.smtp.SMTPSender.SMTPNotSpecified";
        String messageDetail = CommunicatorMessages.getMessage(detailMessageKey);

        throw new MessagingException(messageDetail);
    }
    props.setProperty(SMTP_HOST_KEY, smtpServer);
    int smtpPort = config.getSmtpPort();
    props.setProperty(SMTP_PORT_KEY, String.valueOf(smtpPort));

    // ???????
    Session session = null;
    if (authenticator_ == null) {
        // ?????
        session = Session.getDefaultInstance(props);
    } else {
        // ???
        props.setProperty(SMTP_AUTH_KEY, "true");
        session = Session.getDefaultInstance(props, authenticator_);
    }

    // MIME??
    MimeMessage message = new MimeMessage(session);

    // ??
    // :
    Date date = new Date();
    String encoding = this.config_.getSmtpEncoding();
    message.setHeader("X-Mailer", X_MAILER);
    message.setHeader("Content-Type", "text/plain; charset=\"" + encoding + "\"");
    message.setSentDate(date);

    // :from
    String from = this.config_.getSmtpFrom();
    InternetAddress fromAddr = new InternetAddress(from);
    message.setFrom(fromAddr);

    // :to
    String[] recipients = this.config_.getSmtpTo().split(",");
    for (String toStr : recipients) {
        InternetAddress toAddr = new InternetAddress(toStr);
        message.addRecipient(Message.RecipientType.TO, toAddr);
    }

    // :body, subject
    String subject;
    String body;
    subject = createSubject(entry, date);
    try {
        body = createBody(entry, date);
    } catch (IOException ex) {
        LOGGER.log(LogMessageCodes.FAIL_READ_MAIL_TEMPLATE, "");
        body = createDefaultBody(entry, date);
    }

    message.setSubject(subject, encoding);
    message.setText(body, encoding);

    return message;
}

From source file:mitm.application.djigzo.james.matchers.HasValidPasswordTest.java

@Test
public void testMatchDayValidityInterval() throws MessagingException, EncryptorException {
    HasValidPassword matcher = new HasValidPassword();

    MockMatcherConfig matcherConfig = new MockMatcherConfig("test", "matchOnError=false", mailetContext);

    matcher.init(matcherConfig);// w  ww. ja va 2  s  .co  m

    Mail mail = new MockMail();

    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    message.setContent("test", "text/plain");
    message.setFrom(new InternetAddress("123456@example.com"));

    message.saveChanges();

    mail.setMessage(message);

    Collection<MailAddress> recipients = new LinkedList<MailAddress>();

    recipients.add(new MailAddress("test2@example.com"));

    mail.setRecipients(recipients);

    Collection<?> result = matcher.match(mail);

    assertEquals(1, result.size());
    assertTrue(result.contains(new MailAddress("test2@example.com")));

    DjigzoMailAttributes attributes = new DjigzoMailAttributesImpl(mail);

    Passwords passwords = attributes.getPasswords();

    assertNotNull(passwords);
    assertNotNull(passwords.get("test2@example.com"));
    assertEquals("test2", passwords.get("test2@example.com").getPassword());
    assertEquals("ID2", passwords.get("test2@example.com").getPasswordID());
}

From source file:io.uengine.mail.MailAsyncService.java

@Async
public void download(String type, String version, String token, String subject, String fromUser,
        String fromName, final String toUser, final String toName, InternetAddress[] toCC) {
    Session session = setMailProperties(toUser);

    Map model = new HashMap();
    model.put("link",
            MessageFormatter.arrayFormat("http://www.uengine.io/download/get?type={}&version={}&token={}",
                    new Object[] { type, version, token }).getMessage());
    model.put("name", toName);

    String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "mail/download.vm", "UTF-8",
            model);/*w ww  .  j  a  v  a  2  s  .  c o  m*/

    try {
        InternetAddress from = new InternetAddress(fromUser, fromName);
        MimeMessage message = new MimeMessage(session);
        message.setFrom(from);
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toUser));
        message.setSubject(subject);
        message.setContent(body, "text/html; charset=utf-8");
        if (toCC != null && toCC.length > 0)
            message.setRecipients(Message.RecipientType.CC, toCC);

        Transport.send(message);

        logger.info("{} ? ?? .", toUser);
    } catch (Exception e) {
        throw new ServiceException("??   .", e);
    }
}

From source file:org.openmeetings.test.calendar.TestSendIcalMessage.java

private void sendIcalMessage() throws Exception {

    log.debug("sendIcalMessage");

    // Evaluating Configuration Data
    String smtpServer = cfgManagement.getConfKey(3, "smtp_server").getConf_value();
    String smtpPort = cfgManagement.getConfKey(3, "smtp_port").getConf_value();
    // String from = "openmeetings@xmlcrm.org";
    String from = cfgManagement.getConfKey(3, "system_email_addr").getConf_value();

    String emailUsername = cfgManagement.getConfKey(3, "email_username").getConf_value();
    String emailUserpass = cfgManagement.getConfKey(3, "email_userpass").getConf_value();

    Properties props = System.getProperties();

    props.put("mail.smtp.host", smtpServer);
    props.put("mail.smtp.port", smtpPort);

    Configuration conf = cfgManagement.getConfKey(3, "mail.smtp.starttls.enable");
    if (conf != null) {
        if (conf.getConf_value().equals("1")) {
            props.put("mail.smtp.starttls.enable", "true");
        }//ww w.j  av  a  2  s  .  c o  m
    }

    // Check for Authentification
    Session session = null;
    if (emailUsername != null && emailUsername.length() > 0 && emailUserpass != null
            && emailUserpass.length() > 0) {
        // use SMTP Authentication
        props.put("mail.smtp.auth", "true");
        session = Session.getDefaultInstance(props, new SmtpAuthenticator(emailUsername, emailUserpass));
    } else {
        // not use SMTP Authentication
        session = Session.getDefaultInstance(props, null);
    }

    // Building MimeMessage
    MimeMessage mimeMessage = new MimeMessage(session);
    mimeMessage.setSubject(subject);
    mimeMessage.setFrom(new InternetAddress(from));
    mimeMessage.addRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients, false));

    // -- Create a new message --
    BodyPart msg = new MimeBodyPart();
    msg.setDataHandler(new DataHandler(new ByteArrayDataSource(htmlBody, "text/html; charset=\"utf-8\"")));

    Multipart multipart = new MimeMultipart();

    BodyPart iCalAttachment = new MimeBodyPart();
    iCalAttachment.setDataHandler(new DataHandler(new javax.mail.util.ByteArrayDataSource(
            new ByteArrayInputStream(iCalMimeBody), "text/calendar;method=REQUEST;charset=\"UTF-8\"")));
    iCalAttachment.setFileName("invite.ics");

    multipart.addBodyPart(iCalAttachment);
    multipart.addBodyPart(msg);

    mimeMessage.setSentDate(new Date());
    mimeMessage.setContent(multipart);

    // -- Set some other header information --
    // mimeMessage.setHeader("X-Mailer", "XML-Mail");
    // mimeMessage.setSentDate(new Date());

    // Transport trans = session.getTransport("smtp");
    Transport.send(mimeMessage);

}

From source file:edu.cornell.mannlib.vitro.webapp.controller.freemarker.ContactMailController.java

private void sendMessage(Session s, String webuseremail, String webusername, String[] recipients,
        String deliveryfrom, String msgText) throws AddressException, SendFailedException, MessagingException {
    // Construct the message
    MimeMessage msg = new MimeMessage(s);
    //System.out.println("trying to send message from servlet");

    // Set the from address
    try {/*from ww  w  . ja va  2  s . co m*/
        msg.setFrom(new InternetAddress(webuseremail, webusername));
    } catch (UnsupportedEncodingException e) {
        log.error("Can't set message sender with personal name " + webusername
                + " due to UnsupportedEncodingException");
        msg.setFrom(new InternetAddress(webuseremail));
    }

    // Set the recipient address
    InternetAddress[] address = new InternetAddress[recipients.length];
    for (int i = 0; i < recipients.length; i++) {
        address[i] = new InternetAddress(recipients[i]);
    }
    msg.setRecipients(Message.RecipientType.TO, address);

    // Set the subject and text
    msg.setSubject(deliveryfrom);

    // add the multipart to the message
    msg.setContent(msgText, "text/html");

    // set the Date: header
    msg.setSentDate(new Date());

    Transport.send(msg); // try to send the message via smtp - catch error exceptions

}

From source file:eu.scape_project.planning.user.Groups.java

/**
 * Sends an invitation mail to the user.
 * /*from  ww w. j  av  a  2  s .  c o  m*/
 * @param toUser
 *            the recipient of the mail
 * @param serverString
 *            the server string
 * @return true if the mail was sent successfully, false otherwise
 * @throws InvitationMailException
 *             if the invitation mail could not be send
 */
private void sendInvitationMail(GroupInvitation invitation, String serverString)
        throws InvitationMailException {
    try {
        Properties props = System.getProperties();

        props.put("mail.smtp.host", config.getString("mail.smtp.host"));
        Session session = Session.getDefaultInstance(props, null);

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(config.getString("mail.from")));
        message.setRecipient(RecipientType.TO, new InternetAddress(invitation.getEmail()));
        message.setSubject(
                user.getFullName() + " invited you to join the Plato group " + user.getUserGroup().getName());

        StringBuilder builder = new StringBuilder();
        builder.append("Hello, \n\n");
        builder.append("The Plato user " + user.getFullName() + " has invited you to join the group "
                + user.getUserGroup().getName() + ".\n\n");
        builder.append(
                "You do not seem to be a Plato user. If you would like to accept the invitation, please first create an account at http://"
                        + serverString + "/idp/addUser.jsf.\n");
        builder.append(
                "If you have an account, please log in and use the following link to accept the invitation: \n");
        builder.append("http://" + serverString + "/plato/user/groupInvitation.jsf?uid="
                + invitation.getInvitationActionToken());
        builder.append("\n\n--\n");
        builder.append("Your Planningsuite team");

        message.setText(builder.toString());
        message.saveChanges();

        Transport.send(message);
        log.debug("Group invitation mail sent successfully to " + invitation.getEmail());

    } catch (MessagingException e) {
        log.error("Error sending group invitation mail to " + invitation.getEmail(), e);
        throw new InvitationMailException(e);
    }
}