Example usage for javax.mail.internet MimeMessage setText

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

Introduction

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

Prototype

@Override
public void setText(String text) throws MessagingException 

Source Link

Document

Convenience method that sets the given String as this part's content, with a MIME type of "text/plain".

Usage

From source file:org.apache.james.mailetcontainer.impl.JamesMailetContext.java

/**
 * Generates a bounce mail that is a bounce of the original message.
 *
 * @param bounceText the text to be prepended to the message to describe the bounce
 *                   condition//from  w  w w.j a va  2 s  . co  m
 * @return the bounce mail
 * @throws MessagingException if the bounce mail could not be created
 */
private MailImpl rawBounce(Mail mail, String bounceText) throws MessagingException {
    // This sends a message to the james component that is a bounce of the
    // sent message
    MimeMessage original = mail.getMessage();
    MimeMessage reply = (MimeMessage) original.reply(false);
    reply.setSubject("Re: " + original.getSubject());
    reply.setSentDate(new Date());
    Collection<MailAddress> recipients = new HashSet<MailAddress>();
    recipients.add(mail.getSender());
    InternetAddress addr[] = { new InternetAddress(mail.getSender().toString()) };
    reply.setRecipients(Message.RecipientType.TO, addr);
    reply.setFrom(new InternetAddress(mail.getRecipients().iterator().next().toString()));
    reply.setText(bounceText);
    reply.setHeader(RFC2822Headers.MESSAGE_ID, "replyTo-" + mail.getName());
    return new MailImpl("replyTo-" + mail.getName(),
            new MailAddress(mail.getRecipients().iterator().next().toString()), recipients, reply);
}

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

protected void sendEmail(Email email, List<Email> successfulEmails) {
    try {/*w  ww  .  jav  a2s  . co 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:ar.com.zauber.commons.message.impl.mail.MimeEmailNotificationStrategy.java

/** @see NotificationStrategy#execute(NotificationAddress[], Message) */
public final void execute(final NotificationAddress[] addresses, final Message message) {
    try {//from   w w  w.  jav a  2 s.co m
        final MailSender mailSender = getMailSender();
        //This is ugly....but if it is not a JavaMailSender it will
        //fail (for instance during tests). And the only way to
        //create a Multipartemail is through JavaMailSender
        if (mailSender instanceof JavaMailSender) {
            final JavaMailSender javaMailSender = (JavaMailSender) mailSender;
            final MimeMessage mail = javaMailSender.createMimeMessage();
            final MimeMessageHelper helper = new MimeMessageHelper(mail, true);
            helper.setFrom(getFromAddress().getEmailStr());
            helper.setTo(SimpleEmailNotificationStrategy.getEmailAddresses(addresses));
            helper.setReplyTo(getEmailAddress(message.getReplyToAddress()));
            helper.setSubject(message.getSubject());
            setContent(helper, (MultipartMessage) message);
            addHeaders(message, mail);
            javaMailSender.send(mail);
        } else {
            final SimpleMailMessage mail = new SimpleMailMessage();
            mail.setFrom(getFromAddress().getEmailStr());
            mail.setTo(getEmailAddresses(addresses));
            mail.setReplyTo(getEmailAddress(message.getReplyToAddress()));
            mail.setSubject(message.getSubject());
            mail.setText(message.getContent());
            mailSender.send(mail);
        }
    } catch (final MessagingException e) {
        throw new RuntimeException("Could not send message", e);
    } catch (final UnsupportedEncodingException e) {
        throw new RuntimeException("Could not send message", e);
    }

}

From source file:eu.scape_project.pw.idp.UserManager.java

/**
 * Method responsible for sending a email to the user, including a link to
 * activate his user account.//  ww w . j  a va2 s  . c  o  m
 * 
 * @param user
 *            User the activation mail should be sent to
 * @param serverString
 *            Name and port of the server the user was added.
 * @throws CannotSendMailException
 *             if the mail could not be sent
 */
public void sendActivationMail(IdpUser user, String serverString) throws CannotSendMailException {

    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(user.getEmail()));
        message.setSubject("Please confirm your Planningsuite user account");

        StringBuilder builder = new StringBuilder();
        builder.append("Dear " + user.getFirstName() + " " + user.getLastName() + ", \n\n");
        builder.append("Please use the following link to confirm your Planningsuite user account: \n");
        builder.append("http://" + serverString + "/idp/activateUser.jsf?uid=" + user.getActionToken());
        builder.append("\n\n--\n");
        builder.append("Your Planningsuite team");

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

        Transport.send(message);
        log.debug("Activation mail sent successfully to {}", user.getEmail());
    } catch (Exception e) {
        log.error("Error at sending activation mail to {}", user.getEmail());
        throw new CannotSendMailException("Error at sending activation mail to " + user.getEmail(), e);
    }
}

From source file:it.geosolutions.geobatch.mail.SendMailAction.java

public Queue<EventObject> execute(Queue<EventObject> events) throws ActionException {
    final Queue<EventObject> ret = new LinkedList<EventObject>();

    while (events.size() > 0) {
        final EventObject ev;
        try {/* ww  w  .  jav a2 s.  c o m*/
            if ((ev = events.remove()) != null) {
                if (LOGGER.isTraceEnabled()) {
                    LOGGER.trace("Send Mail action.execute(): working on incoming event: " + ev.getSource());
                }

                File mail = (File) ev.getSource();

                FileInputStream fis = new FileInputStream(mail);
                String kmlURL = IOUtils.toString(fis);

                // /////////////////////////////////////////////
                // Send the mail with the given KML URL
                // /////////////////////////////////////////////

                // Recipient's email ID needs to be mentioned.
                String mailTo = conf.getMailToAddress();

                // Sender's email ID needs to be mentioned
                String mailFrom = conf.getMailFromAddress();

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

                // Setup mail server
                String mailSmtpAuth = conf.getMailSmtpAuth();
                properties.put("mail.smtp.auth", mailSmtpAuth);
                properties.put("mail.smtp.host", conf.getMailSmtpHost());
                properties.put("mail.smtp.starttls.enable", conf.getMailSmtpStarttlsEnable());
                properties.put("mail.smtp.port", conf.getMailSmtpPort());

                // Get the default Session object.
                final String mailAuthUsername = conf.getMailAuthUsername();
                final String mailAuthPassword = conf.getMailAuthPassword();

                Session session = Session.getDefaultInstance(properties,
                        (mailSmtpAuth.equalsIgnoreCase("true") ? new javax.mail.Authenticator() {
                            protected PasswordAuthentication getPasswordAuthentication() {
                                return new PasswordAuthentication(mailAuthUsername, mailAuthPassword);
                            }
                        } : null));

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

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

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

                    // Set Subject: header field
                    message.setSubject(conf.getMailSubject());

                    String mailHeaderName = conf.getMailHeaderName();
                    String mailHeaderValule = conf.getMailHeaderValue();
                    if (mailHeaderName != null && mailHeaderValule != null) {
                        message.addHeader(mailHeaderName, mailHeaderValule);
                    }

                    String mailMessageText = conf.getMailContentHeader();

                    message.setText(mailMessageText + "\n\n" + kmlURL);

                    // Send message
                    Transport.send(message);

                    if (LOGGER.isInfoEnabled())
                        LOGGER.info("Sent message successfully....");

                } catch (MessagingException exc) {
                    ActionExceptionHandler.handleError(conf, this, "An error occurrd when sent message ...");
                    continue;
                }
            } else {
                if (LOGGER.isErrorEnabled()) {
                    LOGGER.error("Send Mail action.execute(): Encountered a NULL event: SKIPPING...");
                }
                continue;
            }
        } catch (Exception ioe) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("Send Mail action.execute(): Unable to produce the output: ",
                        ioe.getLocalizedMessage(), ioe);
            }
            throw new ActionException(this, ioe.getLocalizedMessage(), ioe);
        }
    }

    return ret;
}

From source file:eu.scape_project.pw.idp.UserManager.java

/**
 * Sends the user a link to reset the password.
 * // w  ww .  jav  a 2  s.c  o  m
 * @param user
 *            the user
 * @param serverString
 *            host and port of the server
 * @throws CannotSendMailException
 *             if the password reset mail could not be sent
 */
public void sendPasswordResetMail(IdpUser user, String serverString) throws CannotSendMailException {
    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(user.getEmail()));
        message.setSubject("Planningsuite password recovery");

        StringBuilder builder = new StringBuilder();
        builder.append("Dear " + user.getFirstName() + " " + user.getLastName() + ", \n\n");
        builder.append("You have requested help recovering the password for the Plato user ");
        builder.append(user.getUsername()).append(".\n\n");
        builder.append("Please use the following link to reset your Planningsuite password: \n");
        builder.append("http://" + serverString + "/idp/resetPassword.jsf?uid=" + user.getActionToken());
        builder.append("\n\n--\n");
        builder.append("Your Planningsuite team");

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

        Transport.send(message);
        log.debug("Sent password reset mail to " + user.getEmail());

    } catch (Exception e) {
        log.error("Error at sending password reset mail to {}", user.getEmail());
        throw new CannotSendMailException("Error at sending password reset mail to " + user.getEmail());
    }
}

From source file:com.netflix.genie.server.jobmanager.impl.JobMonitor.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.
 * @return 0 for success, -1 for failure
 *//*from  w w  w . j  a v  a  2 s  .  co m*/
private boolean sendEmail(String emailTo) {
    logger.debug("called");

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

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

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

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

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

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

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

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

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

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

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

    try {
        // Create a default MimeMessage object.
        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));

        // Set Subject: header field
        message.setSubject("Genie Job " + ji.getJobName() + " completed with Status: " + ji.getStatus());

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

        message.setText(body);

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

From source file:org.apache.james.James.java

/**
 * Generates a bounce mail that is a bounce of the original message.
 *
 * @param bounceText the text to be prepended to the message to describe the bounce condition
 *
 * @return the bounce mail/*from   w  w  w.  j a va 2s.c o  m*/
 *
 * @throws MessagingException if the bounce mail could not be created
 */
private MailImpl rawBounce(Mail mail, String bounceText) throws MessagingException {
    //This sends a message to the james component that is a bounce of the sent message
    MimeMessage original = mail.getMessage();
    MimeMessage reply = (MimeMessage) original.reply(false);
    reply.setSubject("Re: " + original.getSubject());
    reply.setSentDate(new Date());
    Collection recipients = new HashSet();
    recipients.add(mail.getSender());
    InternetAddress addr[] = { new InternetAddress(mail.getSender().toString()) };
    reply.setRecipients(Message.RecipientType.TO, addr);
    reply.setFrom(new InternetAddress(mail.getRecipients().iterator().next().toString()));
    reply.setText(bounceText);
    reply.setHeader(RFC2822Headers.MESSAGE_ID, "replyTo-" + mail.getName());
    return new MailImpl("replyTo-" + mail.getName(),
            new MailAddress(mail.getRecipients().iterator().next().toString()), recipients, reply);
}

From source file:eu.scape_project.planning.application.Feedback.java

/**
 * Method responsible for sending feedback per mail.
 * //from  w  w w  .  jav  a2s .  c  o m
 * @param userEmail
 *            email address of the user.
 * @param userComments
 *            comments from the user
 * @param location
 *            the location of the application where the error occurred
 * @param applicationName
 *            the name of the application
 * @throws MailException
 *             if the feedback could not be sent
 */
public void sendFeedback(String userEmail, String userComments, String location, String applicationName)
        throws MailException {

    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(config.getString("mail.feedback")));

        message.setSubject("[" + applicationName + "] from " + location);

        StringBuilder builder = new StringBuilder();
        builder.append("Date: ").append(dateFormat.format(new Date())).append("\n\n");

        // User info
        if (user == null) {
            builder.append("No user available.\n\n");
        } else {
            builder.append("User: ").append(user.getUsername()).append("\n");
            if (user.getUserGroup() != null) {
                builder.append("Group: ").append(user.getUserGroup().getName()).append("\n");
            }
        }
        builder.append("UserMail: ").append(userEmail).append("\n\n");

        // Comments
        builder.append("Comments:\n");
        builder.append(SEPARATOR_LINE);
        builder.append(userComments).append("\n");
        builder.append(SEPARATOR_LINE).append("\n");
        message.setText(builder.toString());
        message.saveChanges();

        Transport.send(message);

        log.debug("Feedback mail sent successfully to {}", config.getString("mail.feedback"));
    } catch (MessagingException e) {
        log.error("Error sending feedback mail to {}", config.getString("mail.feedback"), e);
        throw new MailException("Error sending feedback mail to " + config.getString("mail.feedback"), e);
    }
}

From source file:userInterface.HospitalAdminRole.ManagePatientsJPanel.java

public void sendMailToCommunityMember(String to, String subject, String message, String from, String password) {
    String host = "smtp.gmail.com";
    Properties props = System.getProperties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", 587);
    props.put("mail.smtp.user", from);

    Session session = Session.getDefaultInstance(props);
    MimeMessage mimeMessage = new MimeMessage(session);
    try {//  w  w  w.  j  a va2s .c  o  m
        mimeMessage.setFrom(new InternetAddress(from));
        mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        mimeMessage.setSubject("Alert from Hospital Organization");
        mimeMessage.setText(message);
        SMTPTransport transport = (SMTPTransport) session.getTransport("smtps");
        transport.connect(host, from, password);
        transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
        transport.close();
    } catch (MessagingException me) {

    }
}