Example usage for javax.mail.internet MimeMessage setContent

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

Introduction

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

Prototype

@Override
public void setContent(Multipart mp) throws MessagingException 

Source Link

Document

This method sets the Message's content to a Multipart object.

Usage

From source file:org.apache.hupa.server.preferences.InImapUserPreferencesStorage.java

/**
 * Opens the IMAP folder, deletes all messages which match the magic subject and
 * creates a new message with an attachment which contains the object serialized
 *///from   w w w .j a  v  a  2 s. c  om
protected static void saveUserPreferencesInIMAP(Log logger, User user, Session session, IMAPStore iStore,
        String folderName, String subject, Object object)
        throws MessagingException, IOException, InterruptedException {
    IMAPFolder folder = (IMAPFolder) iStore.getFolder(folderName);

    if (folder.exists() || folder.create(IMAPFolder.HOLDS_MESSAGES)) {
        if (!folder.isOpen()) {
            folder.open(Folder.READ_WRITE);
        }

        // Serialize the object
        ByteArrayOutputStream fout = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(fout);
        oos.writeObject(object);
        oos.close();
        ByteArrayInputStream is = new ByteArrayInputStream(fout.toByteArray());

        // Create a new message with an attachment which has the serialized object
        MimeMessage message = new MimeMessage(session);
        message.setSubject(subject);

        Multipart multipart = new MimeMultipart();
        MimeBodyPart txtPart = new MimeBodyPart();
        txtPart.setContent("This message contains configuration used by Hupa, do not delete it", "text/plain");
        multipart.addBodyPart(txtPart);
        FileItem item = createPreferencesFileItem(is, subject, HUPA_DATA_MIME_TYPE);
        multipart.addBodyPart(MessageUtils.fileitemToBodypart(item));
        message.setContent(multipart);
        message.saveChanges();

        // It seems it's not possible to modify the content of an existing message using the API
        // So I delete the previous message storing the preferences and I create a new one
        Message[] msgs = folder.getMessages();
        for (Message msg : msgs) {
            if (subject.equals(msg.getSubject())) {
                msg.setFlag(Flag.DELETED, true);
            }
        }

        // It is necessary to copy the message before saving it (the same problem in AbstractSendMessageHandler)
        message = new MimeMessage((MimeMessage) message);
        message.setFlag(Flag.SEEN, true);
        folder.appendMessages(new Message[] { message });
        folder.close(true);
        logger.info("Saved preferences " + subject + " in imap folder " + folderName + " for user " + user);
    } else {
        logger.error("Unable to save preferences " + subject + " in imap folder " + folderName + " for user "
                + user);
    }
}

From source file:com.cisco.dbds.utils.report.CustomReport.java

/**
 * Sendmail./*from  w  w  w  . j av a 2 s .  co m*/
 *
 * @param msg the msg
 * @throws AddressException the address exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void sendmail(String msg) throws AddressException, IOException {
    //Properties CustomReport_CONFIG = new Properties();
    //FileInputStream fn = new FileInputStream(System.getProperty("user.dir")+ "/src/it/resources/config.properties");
    //CustomReport_CONFIG.load(fn);
    String from = "automationreportmailer@cisco.com";
    // String from = "sitaut@cisco.com";
    //String host = System.getProperty("MAIL.SMTP.HOST");
    String host = "outbound.cisco.com";
    // Mail to details
    Properties properties = System.getProperties();
    properties.setProperty("mail.smtp.host", host);
    // String ecsip = CustomReport_CONFIG.getProperty("ecsip");
    javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties);

    // compose the message
    try {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from
        // ));
                , "Automation Report Mailer"));
        //message.addRecipients(Message.RecipientType.TO, System.getProperty("MAIL.TO"));
        //message.setSubject(System.getProperty("mail.subject"));

        message.addRecipients(Message.RecipientType.TO, "maparame@cisco.com");
        message.setSubject("VCS consle report");
        Multipart mp = new MimeMultipart();
        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(msg, "text/html");
        mp.addBodyPart(htmlPart);
        message.setContent(mp);
        Transport.send(message);
        System.out.println(msg);
        System.out.println("message sent successfully....");

    } catch (MessagingException mex) {
        mex.printStackTrace();
    } catch (Exception e) {
        System.out.println("\tException in sending mail to configured mailers list");
    }
}

From source file:AmazonSESSample.java

private static RawMessage getRawMessage() throws MessagingException, IOException {
    // JavaMail representation of the message
    Session s = Session.getInstance(new Properties(), null);
    s.setDebug(true);/* w ww.  jav  a  2  s .  com*/
    MimeMessage msg = new MimeMessage(s);

    // Sender and recipient
    msg.setFrom(new InternetAddress("aravind@gofastpay.com"));
    InternetAddress[] address = { new InternetAddress("aravind@gofastpay.com") };
    msg.setRecipients(javax.mail.Message.RecipientType.TO, address);
    msg.setSentDate(new Date());
    // Subject
    msg.setSubject(SUBJECT);

    // Add a MIME part to the message
    //MimeMultipart mp = new MimeMultipart();
    Multipart mp = new MimeMultipart();
    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    //mimeBodyPart.setText(BODY);

    //BodyPart part = new MimeBodyPart();
    //String myText = BODY;
    //part.setContent(URLEncoder.encode(myText, "US-ASCII"), "text/html");
    //part.setText(BODY);
    //mp.addBodyPart(part);
    //msg.setContent(mp);
    mimeBodyPart.setContent(BODY, "text/html");
    mp.addBodyPart(mimeBodyPart);
    msg.setContent(mp);

    // Print the raw email content on the console
    //PrintStream out = System.out;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    msg.writeTo(out);
    //String rawString = out.toString();
    //byte[] bytes = IOUtils.toByteArray(msg.getInputStream());
    //ByteBuffer byteBuffer = ByteBuffer.allocate(bytes.length);
    //ByteBuffer byteBuffer = ByteBuffer.wrap(Base64.getEncoder().encode(rawString.getBytes()));

    //byteBuffer.put(bytes);
    //byteBuffer.put(Base64.getEncoder().encode(bytes));
    RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(out.toByteArray()));
    return rawMessage;
}

From source file:org.apache.lens.server.query.QueryEndNotifier.java

/** Send mail.
 *
 * @param host                      the host
 * @param port                      the port
 * @param email                     the email
 * @param mailSmtpTimeout           the mail smtp timeout
 * @param mailSmtpConnectionTimeout the mail smtp connection timeout */
public static void sendMail(String host, String port, Email email, int mailSmtpTimeout,
        int mailSmtpConnectionTimeout) throws Exception {
    Properties props = System.getProperties();
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);
    props.put("mail.smtp.timeout", mailSmtpTimeout);
    props.put("mail.smtp.connectiontimeout", mailSmtpConnectionTimeout);
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(email.getFrom()));
    for (String recipient : email.getTo().trim().split("\\s*,\\s*")) {
        message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
    }//from   w w  w .j ava  2s.c om
    if (email.getCc() != null && email.getCc().length() > 0) {
        for (String recipient : email.getCc().trim().split("\\s*,\\s*")) {
            message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(recipient));
        }
    }
    message.setSubject(email.getSubject());
    message.setSentDate(new Date());

    MimeBodyPart messagePart = new MimeBodyPart();
    messagePart.setText(email.getMessage());
    Multipart multipart = new MimeMultipart();

    multipart.addBodyPart(messagePart);
    message.setContent(multipart);
    Transport.send(message);
}

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");
        }/*from   w w w. j a va2 s . com*/
    });
    //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:com.email.SendEmailCalInvite.java

/**
 * Sends email based off of the section it comes from. This creates a
 * calendar invite object that is interactive by Outlook.
 *
 * @param eml EmailOutInviteModel/*w ww  . ja  v a 2  s  .  c  o  m*/
 */
public static void sendCalendarInvite(EmailOutInvitesModel eml) {
    SystemEmailModel account = null;

    //Get Account
    for (SystemEmailModel acc : Global.getSystemEmailParams()) {
        if (acc.getSection().equals(eml.getSection())) {
            account = acc;
            break;
        }
    }
    if (account != null) {
        //Get parts
        String FromAddress = account.getEmailAddress();
        String[] TOAddressess = ((eml.getToAddress() == null) ? "".split(";") : eml.getToAddress().split(";"));
        String[] CCAddressess = ((eml.getCcAddress() == null) ? "".split(";") : eml.getCcAddress().split(";"));
        String emailSubject = "";
        BodyPart emailBody = body(eml);
        BodyPart inviteBody = null;

        if (eml.getHearingRoomAbv() == null) {
            emailSubject = eml.getEmailSubject() == null
                    ? (eml.getEmailBody() == null ? eml.getCaseNumber() : eml.getEmailBody())
                    : eml.getEmailSubject();
            inviteBody = responseDueCalObject(eml, account);
        } else {
            emailSubject = eml.getEmailSubject() == null ? Subject(eml) : eml.getEmailSubject();
            inviteBody = inviteCalObject(eml, account, emailSubject);
        }

        //Set Email Parts
        Authenticator auth = EmailAuthenticator.setEmailAuthenticator(account);
        Properties properties = EmailProperties.setEmailOutProperties(account);
        Session session = Session.getInstance(properties, auth);
        MimeMessage smessage = new MimeMessage(session);
        Multipart multipart = new MimeMultipart("alternative");
        try {
            smessage.addFrom(new InternetAddress[] { new InternetAddress(FromAddress) });
            for (String To : TOAddressess) {
                if (EmailValidator.getInstance().isValid(To)) {
                    smessage.addRecipient(Message.RecipientType.TO, new InternetAddress(To));
                }
            }
            for (String Cc : CCAddressess) {
                if (EmailValidator.getInstance().isValid(Cc)) {
                    smessage.addRecipient(Message.RecipientType.CC, new InternetAddress(Cc));
                }
            }
            smessage.setSubject(emailSubject);
            multipart.addBodyPart(emailBody);
            multipart.addBodyPart(inviteBody);
            smessage.setContent(multipart);
            if (Global.isOkToSendEmail()) {
                Transport.send(smessage);
            } else {
                Audit.addAuditEntry("Cal Invite Not Actually Sent: " + eml.getId() + " - " + emailSubject);
            }
            EmailOutInvites.deleteEmailEntry(eml.getId());
        } catch (AddressException ex) {
            ExceptionHandler.Handle(ex);
        } catch (MessagingException ex) {
            ExceptionHandler.Handle(ex);
        }
    }
}

From source file:gmailclientfx.core.GmailClient.java

public static void sendMessage(String to, String subject, String body, List<String> attachments)
        throws Exception {
    // authenticate with gmail smtp server
    SMTPTransport smtpTransport = connectToSmtp("smtp.gmail.com", 587, EMAIL, ACCESS_TOKEN, true);

    // kreiraj MimeMessage objekt
    MimeMessage msg = new MimeMessage(OAuth2Authenticator.getSession());

    // dodaj headere
    msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
    msg.addHeader("format", "flowed");
    msg.addHeader("Content-Transfer-Encoding", "8bit");

    msg.setFrom(new InternetAddress(EMAIL));
    msg.setRecipients(javax.mail.Message.RecipientType.CC, InternetAddress.parse(to));
    msg.setSubject(subject, "UTF-8");
    msg.setReplyTo(InternetAddress.parse(EMAIL, false));

    // tijelo poruke
    BodyPart msgBodyPart = new MimeBodyPart();
    msgBodyPart.setText(body);/*from w w w  .j  a v a 2  s  .co m*/

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(msgBodyPart);
    msg.setContent(multipart);

    // dodaj privitke
    if (attachments.size() > 0) {
        for (String attachment : attachments) {
            msgBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(attachment);
            msgBodyPart.setDataHandler(new DataHandler(source));
            msgBodyPart.setFileName(source.getName());
            multipart.addBodyPart(msgBodyPart);
        }
        msg.setContent(multipart);
    }
    smtpTransport.sendMessage(msg, InternetAddress.parse(to));

    Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
    alert.setTitle("Poruka poslana!");
    alert.setHeaderText(null);
    alert.setContentText("Email uspjeno poslan!");
    alert.showAndWait();
}

From source file:com.synyx.greetingcard.mail.OpenCmsMailService.java

public void sendMultipartMail(MessageConfig config, DataSource ds, String filename) throws MessagingException {
    log.debug("Sending multipart message " + config);

    Session session = getSession();/*w  ww .j a  va2 s  .c o m*/
    MimeMultipart multipart = new MimeMultipart();
    MimeBodyPart html = new MimeBodyPart();
    html.setContent(config.getContent(), config.getContentType());
    html.setHeader("MIME-Version", "1.0");
    html.setHeader("Content-Type", html.getContentType());
    multipart.addBodyPart(html);

    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setDataHandler(new DataHandler(ds));
    messageBodyPart.setFileName(filename);
    multipart.addBodyPart(messageBodyPart);

    final MimeMessage message = new MimeMessage(session);
    message.setContent(multipart);
    try {
        message.setFrom(new InternetAddress(config.getFrom(), config.getFromName()));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(config.getTo(), config.getToName()));
    } catch (UnsupportedEncodingException ex) {
        throw new MessagingException("Setting from or to failed", ex);
    }

    message.setSubject(config.getSubject());

    // we don't send in a new Thread so that we get the Exception
    Transport.send(message);
}

From source file:org.tizzit.util.mail.MailHelper.java

/**
 * Send an email in html-format in iso-8859-1-encoding
 * // w w w.j  a  v a 2s.c  o  m
 * @param subject the subject of the new mail
 * @param htmlMessage the content of the mail as html
 * @param alternativeTextMessage the content of the mail as text
 * @param from the sender-address
 * @param to the receiver-address
 * @param cc the address of the receiver of a copy of this mail
 * @param bcc the address of the receiver of a blind-copy of this mail
 */
public static void sendHtmlMail(String subject, String htmlMessage, String alternativeTextMessage, String from,
        String to, String cc, String bcc) {
    try {
        MimeMessage msg = new MimeMessage(mailSession);
        msg.setFrom(new InternetAddress(from));
        if (cc != null && !cc.equals(""))
            msg.setRecipients(Message.RecipientType.CC, cc);
        if (bcc != null && !bcc.equals(""))
            msg.setRecipients(Message.RecipientType.BCC, bcc);
        msg.addRecipients(Message.RecipientType.TO, to);
        msg.setSubject(subject, "iso-8859-1");
        msg.setSentDate(new Date());

        MimeMultipart multiPart = new MimeMultipart();
        BodyPart bodyPart = new MimeBodyPart();

        bodyPart.setText(alternativeTextMessage);
        multiPart.addBodyPart(bodyPart);

        bodyPart = new MimeBodyPart();
        bodyPart.setContent(htmlMessage, "text/html");
        multiPart.addBodyPart(bodyPart);

        multiPart.setSubType("alternative");

        msg.setContent(multiPart);
        Transport.send(msg);
    } catch (Exception e) {
        log.error("Error sending html-mail: " + e.getLocalizedMessage());
    }
}

From source file:com.formkiq.core.service.notification.ExternalMailSender.java

/**
 * Send Reset Email.//from  w  ww . j av a2 s.  c o  m
 * @param to {@link String}
 * @param email {@link String}
 * @param subject {@link String}
 * @param text {@link String}
 * @param html {@link String}
 * @throws MessagingException MessagingException
 */
private void sendResetEmail(final String to, final String email, final String subject, final String text,
        final String html) throws MessagingException {

    String hostname = this.systemProperties.getSystemHostname();
    String resetToken = this.userservice.generateResetToken(to);

    StringSubstitutor s = new StringSubstitutor(
            ImmutableMap.of("hostname", hostname, "to", to, "email", email, "resettoken", resetToken));

    MimeBodyPart textPart = new MimeBodyPart();
    textPart.setText(s.replace(text), "UTF-8");

    s.replace(html);
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(s.replace(html), "text/html;charset=UTF-8");

    final Multipart mp = new MimeMultipart("alternative");
    mp.addBodyPart(textPart);
    mp.addBodyPart(htmlPart);

    MimeMessage msg = this.mail.createMimeMessage();
    msg.setContent(mp);

    msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

    msg.setSubject(subject);

    this.mail.send(msg);
}