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:org.cloudcoder.healthmonitor.HealthMonitor.java

private void sendEmail(Map<String, Info> infoMap, List<ReportItem> reportItems, boolean goodNews,
        boolean badNews, String reportEmailAddress) throws MessagingException, AddressException {
    Session session = createMailSession(config);

    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(reportEmailAddress));
    message.addRecipient(RecipientType.TO, new InternetAddress(reportEmailAddress));
    message.setSubject("CloudCoder health monitor report");

    StringBuilder body = new StringBuilder();
    body.append("<h1>CloudCoder health monitor report</h1>\n");

    if (badNews) {
        body.append("<h2>Unhealthy instances</h2>\n");
        body.append("<ul>\n");
        for (ReportItem item : reportItems) {
            if (item.badNews()) {
                appendReportItem(body, item, infoMap);
            }/*from w ww . j  a v  a2 s . co m*/
        }
        body.append("</ul>\n");
    }

    if (goodNews) {
        body.append("<h2>Healthy instances (back on line)</h2>\n");
        body.append("<ul>\n");
        for (ReportItem item : reportItems) {
            if (item.goodNews()) {
                appendReportItem(body, item, infoMap);
            }
        }
        body.append("</ul>\n");
    }

    message.setContent(body.toString(), "text/html");

    Transport.send(message);
}

From source file:mitm.application.djigzo.james.mailets.RequestSenderCertificateTest.java

@Test
public void testRequestCertificatePendingAvailable() throws Exception {
    MockMailetConfig mailetConfig = new MockMailetConfig();

    String from = "from@example.com";
    String to = "to@example.com";

    proxy.addCertificateRequest(from);/* w  ww . jav a 2 s.co m*/

    RequestSenderCertificate mailet = new RequestSenderCertificate();

    mailet.init(mailetConfig);

    MockMail mail = new MockMail();

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

    message.setContent("test", "text/plain");
    message.setFrom(new InternetAddress(from));

    message.saveChanges();

    mail.setMessage(message);

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

    recipients.add(new MailAddress(to));

    mail.setRecipients(recipients);

    mail.setSender(new MailAddress("somethingelse@example.com"));

    assertFalse(proxy.isUser(from));
    assertFalse(proxy.isUser(to));

    mailet.service(mail);

    assertEquals(INITIAL_KEY_STORE_SIZE, proxy.getKeyAndCertStoreSize());

    assertFalse(proxy.isUser(to));
    assertFalse(proxy.isUser(from));
}

From source file:com.ilopez.jasperemail.JasperEmail.java

public void emailReport(String emailHost, final String emailUser, final String emailPass,
        Set<String> emailRecipients, String emailSender, String emailSubject, List<String> attachmentFileNames,
        Boolean smtpauth, OptionValues.SMTPType smtpenc, Integer smtpport) throws MessagingException {

    Logger.getLogger(JasperEmail.class.getName()).log(Level.INFO, emailHost + " " + emailUser + " " + emailPass
            + " " + emailSender + " " + emailSubject + " " + smtpauth + " " + smtpenc + " " + smtpport);
    Properties props = new Properties();

    // Setup Email Settings
    props.setProperty("mail.smtp.host", emailHost);
    props.setProperty("mail.smtp.port", smtpport.toString());
    props.setProperty("mail.smtp.auth", smtpauth.toString());

    if (smtpenc == OptionValues.SMTPType.SSL) {
        // SSL settings
        props.put("mail.smtp.socketFactory.port", smtpport.toString());
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    } else if (smtpenc == OptionValues.SMTPType.TLS) {
        // TLS Settings
        props.put("mail.smtp.starttls.enable", "true");
    } else {/*from  w  w  w.  j av a 2s. co  m*/
        // Plain
    }

    // Setup and Apply the Email Authentication

    Session mailSession = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(emailUser, emailPass);
        }
    });

    MimeMessage message = new MimeMessage(mailSession);
    message.setSubject(emailSubject);
    for (String emailRecipient : emailRecipients) {
        Address toAddress = new InternetAddress(emailRecipient);
        message.addRecipient(Message.RecipientType.TO, toAddress);
    }
    Address fromAddress = new InternetAddress(emailSender);
    message.setFrom(fromAddress);
    // Message text
    Multipart multipart = new MimeMultipart();
    BodyPart textBodyPart = new MimeBodyPart();
    textBodyPart.setText("Database report attached\n\n");
    multipart.addBodyPart(textBodyPart);
    // Attachments
    for (String attachmentFileName : attachmentFileNames) {
        BodyPart attachmentBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(attachmentFileName);
        attachmentBodyPart.setDataHandler(new DataHandler(source));
        String fileNameWithoutPath = attachmentFileName.replaceAll("^.*\\/", "");
        fileNameWithoutPath = fileNameWithoutPath.replaceAll("^.*\\\\", "");
        attachmentBodyPart.setFileName(fileNameWithoutPath);
        multipart.addBodyPart(attachmentBodyPart);
    }
    // add parts to message
    message.setContent(multipart);
    // send via SMTP
    Transport transport = mailSession.getTransport("smtp");

    transport.connect();
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
}

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 ww  w.  ja  va2  s  .co m

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

From source file:mitm.application.djigzo.james.mailets.SMIMEEncrypt.java

@Override
public void serviceMail(Mail mail) {
    try {//from w w  w .  j  a  va  2  s  . c  o  m
        DjigzoMailAttributes mailAttributes = new DjigzoMailAttributesImpl(mail);

        Certificates certificateStore = mailAttributes.getCertificates();

        if (certificateStore != null) {
            Collection<X509Certificate> certificates = certificateStore.getCertificates();

            if (certificates.size() > 0) {
                MimeMessage message = mail.getMessage();

                if (message != null) {
                    SMIMEBuilder sMIMEBuilder = new SMIMEBuilderImpl(message, getProtectedHeaders(mail));

                    sMIMEBuilder.setUseDeprecatedContentTypes(useDeprecatedContentTypes);

                    for (X509Certificate certificate : certificates) {
                        sMIMEBuilder.addRecipient(certificate, getRecipientMode());
                    }

                    SMIMEEncryptionAlgorithm localAlgorithm = getEncryptionAlgorithm(mail);

                    int localKeySize = (keySize != null ? keySize : localAlgorithm.defaultKeySize());

                    getLogger().debug("Encrypting the message. Encryption algorithm: {}, key size: {}",
                            localAlgorithm, localKeySize);

                    sMIMEBuilder.encrypt(localAlgorithm, localKeySize);

                    MimeMessage encrypted = sMIMEBuilder.buildMessage();

                    if (encrypted != null) {
                        encrypted.saveChanges();

                        /*
                         * A new MimeMessage instance will be created. This makes ure that the 
                         * MimeMessage can be written by James (using writeTo()). The message-ID
                         * of the source message will be retained if told to do so
                         */
                        encrypted = retainMessageID ? new MimeMessageWithID(encrypted, message.getMessageID())
                                : new MimeMessage(encrypted);

                        mail.setMessage(encrypted);
                    }
                } else {
                    getLogger().warn("Message is null.");
                }
            } else {
                getLogger().warn("Certificate collection is empty.");
            }
        } else {
            getLogger().warn("Certificates attribute not found.");
        }
    } catch (SMIMEBuilderException e) {
        getLogger().error("Error encrypting the message.", e);
    } catch (MessagingException e) {
        getLogger().error("Error reading the message.", e);
    } catch (IOException e) {
        getLogger().error("IOException.", e);
    }
}

From source file:com.threewks.thundr.gmail.GmailMailer.java

private MimeMessage createMime(String bodyText, String subject, Map<String, String> to, List<Attachment> pdfs)
        throws MessagingException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage email = new MimeMessage(session);
    Set<InternetAddress> toAddresses = getInternetAddresses(to);

    if (!toAddresses.isEmpty()) {
        email.addRecipients(javax.mail.Message.RecipientType.TO,
                toAddresses.toArray(new InternetAddress[to.size()]));
    }/*from   w w w .  ja v  a 2  s .c om*/

    email.setSubject(subject);

    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent(bodyText, "text/html");
    mimeBodyPart.setHeader("Content-Type", "text/html; charset=\"UTF-8\"");

    Multipart multipart = new MimeMultipart();
    for (Attachment attachmentPdf : pdfs) {
        MimeBodyPart attachment = new MimeBodyPart();
        DataSource source = new ByteArrayDataSource(attachmentPdf.getData(), "application/pdf");
        attachment.setDataHandler(new DataHandler(source));
        attachment.setFileName(attachmentPdf.getFileName());
        multipart.addBodyPart(mimeBodyPart);
        multipart.addBodyPart(attachment);
    }
    email.setContent(multipart);
    return email;
}

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

/**
 * Sends an invitation mail to the user.
 * /*from w  w  w  . ja v a2  s . c om*/
 * @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(User toUser, 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("Dear " + toUser.getFullName() + ", \n\n");
        builder.append("The Plato user " + user.getFullName() + " has invited you to join the group "
                + user.getUserGroup().getName() + ".\n");
        builder.append("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 (Exception e) {
        log.error("Error sending group invitation mail to " + invitation.getEmail(), e);
        throw new InvitationMailException(e);
    }
}

From source file:frameworkcontentspeed.Utils.SendEmailAtachament.java

public static void SendEmailSephoraFailed(String adresaSephora, String from, String to1, String to2,
        String grupSephora, String subject, String filename) throws FileNotFoundException, IOException {

    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");
    //get Session   
    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(from, "anda.cristea");
        }//  w ww . j  a  v  a  2s.c o  m
    });
    //compose message    
    try {
        MimeMessage message = new MimeMessage(session);
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to1));

        message.setSubject(subject);
        // message.setText(msg);

        BodyPart messageBodyPart = new MimeBodyPart();

        messageBodyPart.setText("Raport teste automate");

        Multipart multipart = new MimeMultipart();

        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();

        DataSource source = new FileDataSource(filename);

        messageBodyPart.setDataHandler(new DataHandler(source));

        messageBodyPart.setFileName(filename);

        multipart.addBodyPart(messageBodyPart);

        message.setContent(multipart);

        //send message  
        Transport.send(message);

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

}

From source file:TestOpenMailRelay.java

private void finish() {

    // Create the Session object
    session = Session.getDefaultInstance(props, null);
    // session.setDebug(true);      // Verbose!

    // create a message
    mesg = new MimeMessage(session);
}

From source file:com.netflix.genie.server.jobmanager.impl.JobMonitorImpl.java

/**
 * Check the properties file to figure out if an email needs to be sent at
 * the end of the job. If yes, get mail properties and try and send email
 * about Job Status.//from w  w w .ja  va 2  s  . c  om
 *
 * @return 0 for success, -1 for failure
 * @throws GenieException on issue
 */
private boolean sendEmail(final String emailTo, final boolean killed) throws GenieException {
    LOG.debug("called");
    final Job job = this.jobService.getJob(this.jobId);

    if (!this.config.getBoolean("com.netflix.genie.server.mail.enable", false)) {
        LOG.warn("Email is disabled but user has specified an email address.");
        return false;
    }

    // Sender's email ID
    final String fromEmail = this.config.getString("com.netflix.genie.server.mail.smpt.from",
            "no-reply-genie@geniehost.com");
    LOG.info("From email address to use to send email: " + fromEmail);

    // Set the smtp server hostname. Use localhost as default
    final String smtpHost = this.config.getString("com.netflix.genie.server.mail.smtp.host", "localhost");
    LOG.debug("Email smtp server: " + smtpHost);

    // Get system properties
    final Properties properties = new Properties();

    // Setup mail server
    properties.setProperty("mail.smtp.host", smtpHost);

    // check whether authentication should be turned on
    Authenticator auth = null;

    if (this.config.getBoolean("com.netflix.genie.server.mail.smtp.auth", false)) {
        LOG.debug("Email Authentication Enabled");

        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.auth", "true");

        final String userName = config.getString("com.netflix.genie.server.mail.smtp.user");
        final String password = config.getString("com.netflix.genie.server.mail.smtp.password");

        if (userName == null || password == null) {
            LOG.error("Authentication is enabled and username/password for smtp server is null");
            return false;
        }
        LOG.debug("Constructing authenticator object with username" + userName + " and password " + password);
        auth = new SMTPAuthenticator(userName, password);
    } else {
        LOG.debug("Email authentication not enabled.");
    }

    // Get the default Session object.
    final Session session = Session.getInstance(properties, auth);

    try {
        // Create a default MimeMessage object.
        final MimeMessage message = new MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(fromEmail));

        // Set To: header field of the header.
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailTo));

        JobStatus jobStatus;

        if (killed) {
            jobStatus = JobStatus.KILLED;
        } else {
            jobStatus = job.getStatus();
        }

        // Set Subject: header field
        message.setSubject("Genie Job " + job.getName() + " completed with Status: " + jobStatus);

        // Now set the actual message
        final String body = "Your Genie Job is complete\n\n" + "Job ID: " + job.getId() + "\n" + "Job Name: "
                + job.getName() + "\n" + "Status: " + job.getStatus() + "\n" + "Status Message: "
                + job.getStatusMsg() + "\n" + "Output Base URL: " + job.getOutputURI() + "\n";

        message.setText(body);

        // Send message
        Transport.send(message);
        LOG.info("Sent email message successfully....");
        return true;
    } catch (final MessagingException mex) {
        LOG.error("Got exception while sending email", mex);
        return false;
    }
}