Example usage for javax.mail.internet MimeMessage setSubject

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

Introduction

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

Prototype

@Override
public void setSubject(String subject) throws MessagingException 

Source Link

Document

Set the "Subject" header field.

Usage

From source file:gwtupload.sendmailsample.server.SendMailSampleServlet.java

@Override
public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles)
        throws UploadActionException {
    try {//ww  w. java  2s  .c  o  m
        String from = null, to = null, subject = "", body = "";
        // create a new multipart content
        MimeMultipart multiPart = new MimeMultipart();
        for (FileItem item : sessionFiles) {
            if (item.isFormField()) {
                if ("from".equals(item.getFieldName()))
                    from = item.getString();
                if ("to".equals(item.getFieldName()))
                    to = item.getString();
                if ("subject".equals(item.getFieldName()))
                    subject = item.getString();
                if ("body".equals(item.getFieldName()))
                    body = item.getString();
            } else {
                // add the file part to multipart content
                MimeBodyPart part = new MimeBodyPart();
                part.setFileName(item.getName());
                part.setDataHandler(
                        new DataHandler(new ByteArrayDataSource(item.get(), item.getContentType())));
                multiPart.addBodyPart(part);
            }
        }

        // add the text part to multipart content
        MimeBodyPart txtPart = new MimeBodyPart();
        txtPart.setContent(body, "text/plain");
        multiPart.addBodyPart(txtPart);

        // configure smtp server
        Properties props = System.getProperties();
        props.put("mail.smtp.host", SMTP_SERVER);
        // create a new mail session and the mime message
        MimeMessage mime = new MimeMessage(Session.getInstance(props));
        mime.setText(body);
        mime.setContent(multiPart);
        mime.setSubject(subject);
        mime.setFrom(new InternetAddress(from));
        for (String rcpt : to.split("[\\s;,]+"))
            mime.addRecipient(Message.RecipientType.TO, new InternetAddress(rcpt));
        // send the message
        Transport.send(mime);
    } catch (MessagingException e) {
        throw new UploadActionException(e.getMessage());
    }
    return "Your mail has been sent successfuly.";
}

From source file:org.ktunaxa.referral.server.command.test.TestEmailCommand.java

@Override
public void execute(TestEmailRequest request, TestEmailResponse response) throws Exception {
    final String from = "rms@ktunaxa.org";
    final String to = request.getTo();
    if (null == to) {
        throw new GeomajasException(ExceptionCode.PARAMETER_MISSING, "to");
    }/*from  w w  w. j  av  a 2 s. co  m*/
    MimeMessagePreparator preparator = new MimeMessagePreparator() {

        public void prepare(MimeMessage mimeMessage) throws Exception {

            mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            mimeMessage.setFrom(new InternetAddress(from));
            mimeMessage.setSubject("Test");
            mimeMessage.setText("Testing RMS");
        }
    };
    mailSender.send(preparator);
}

From source file:com.mgmtp.jfunk.core.reporting.EmailReporter.java

private void sendMessage(final String content) {
    try {/*w w  w .  j av  a 2 s. co m*/
        MimeMessage msg = new MimeMessage(sessionProvider.get());
        msg.setSubject("jFunk E-mail Report");
        msg.addRecipients(Message.RecipientType.TO, recipientsProvider.get());

        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(content, "text/html; charset=UTF-8");

        MimeMultipart multipart = new MimeMultipart("related");
        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();
        messageBodyPart.setDataHandler(new DataHandler(getClass().getResource("check.gif")));
        messageBodyPart.setHeader("Content-ID", "<check>");
        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();
        messageBodyPart.setDataHandler(new DataHandler(getClass().getResource("error.gif")));
        messageBodyPart.setHeader("Content-ID", "<error>");
        multipart.addBodyPart(messageBodyPart);

        msg.setContent(multipart);

        smtpClientProvider.get().send(msg);

        int anzahlRecipients = msg.getAllRecipients().length;
        log.info(
                "Report e-mail was sent to " + anzahlRecipients + " recipient(s): " + recipientsProvider.get());
    } catch (MessagingException e) {
        log.error("Error while creating report e-mail", e);
    } catch (MailException e) {
        log.error("Error while sending report e-mail", e);
    }
}

From source file:controllerClasses.security.SiteuserControl.java

private void sendMail(String email, String subject, String body)
        throws NamingException, javax.mail.MessagingException {

    javax.mail.internet.MimeMessage message = new javax.mail.internet.MimeMessage(mailAOSMail);
    message.setSubject(subject);
    message.setRecipients(javax.mail.Message.RecipientType.TO,
            javax.mail.internet.InternetAddress.parse(email, false));
    message.setContent(body, "text/html");
    javax.mail.Transport.send(message);/*from  ww  w.j  av  a  2 s .c o m*/
}

From source file:org.apache.axis2.transport.mail.MailClient.java

public void sendMessage(String to, String subject, String content, String soapAction)
        throws MessagingException {
    log.info("SENDING message from " + from + " to " + to);

    MimeMessage msg = new MimeMessage(session);

    msg.setHeader("transport.mail.soapaction", soapAction);
    msg.addRecipients(Message.RecipientType.TO, to);
    msg.setSubject(subject);
    msg.setText(content);/*  ww w  .j a  va  2s  . c  om*/
    Transport.send(msg);
}

From source file:org.rhq.enterprise.server.core.EmailManagerBean.java

/**
 * Send email to the addressses passed in toAddresses with the passed subject and body. Invalid emails will
 * be reported back. This can only catch sender errors up to the first smtp gateway.
 * @param  toAddresses list of email addresses to send to
 * @param  messageSubject subject of the email sent
 * @param  messageBody body of the email to be sent
 *
 * @return list of email receivers for which initial delivery failed.
 *///from   w  ww.  j  a  v  a 2 s .  c  o  m
public Collection<String> sendEmail(Collection<String> toAddresses, String messageSubject, String messageBody) {

    MimeMessage mimeMessage = new MimeMessage(mailSession);
    try {
        mimeMessage.setSubject(messageSubject);
        mimeMessage.setContent(messageBody, "text/plain");
    } catch (MessagingException e) {
        e.printStackTrace(); // TODO: Customise this generated block
        return toAddresses;
    }

    Exception error = null;
    Collection<String> badAdresses = new ArrayList<String>(toAddresses.size());

    // Send to each recipient individually, do not throw exceptions until we try them all
    for (String toAddress : toAddresses) {
        try {
            LOG.debug("Sending email [" + messageSubject + "] to recipient [" + toAddress + "]");
            InternetAddress recipient = new InternetAddress(toAddress);
            Transport.send(mimeMessage, new InternetAddress[] { recipient });
        } catch (Exception e) {
            LOG.error("Failed to send email [" + messageSubject + "] to recipient [" + toAddress + "]: "
                    + e.getMessage());
            badAdresses.add(toAddress);

            // Remember the first error - in case its due to a session initialization problem,
            // we don't want to lose the first error.
            if (error == null) {
                error = e;
            }
        }
    }

    if (error != null) {
        LOG.error("Sending of emails failed for this reason: " + error.getMessage());
    }

    return badAdresses;
}

From source file:com.unilever.audit.services2.ForgetPassword.java

@GET
@Path("Email/{email}")
@Produces("application/json")
public String LoginIn(@PathParam("email") String email) throws IOException {
    boolean status = true;
    String error = null;//from  w w w . jav a2s.  c  om
    JSONObject result = new JSONObject();

    Map<String, Object> hm = new HashMap<String, Object>();
    hm.put("email", email);
    Merchandisers merchidisers = (Merchandisers) merchandisersFacadeREST
            .findOneByQuery("Merchandisers.findByEmail", hm);
    if (merchidisers == null) {
        status = false;
        error = "invalid email";
    } else {
        Properties props = new Properties();
        final String from = "";
        final String password = "";
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.user", from);
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.password", password);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");

        Session session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, password);
            }
        });
        session.setDebug(true);
        try {
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom();
            msg.setRecipients(Message.RecipientType.TO, email);
            msg.setSubject("Unilever Confirmation");
            msg.setSentDate(new Date());
            msg.setText("");
            Transport.send(msg);
        } catch (MessagingException ex) {
            //  status = false;
            //  error="Error Sending Email";
            ex.printStackTrace();
        }
    }
    result.put("status", status);
    result.put("error", error);
    System.out.println("----------------" + result.toString());
    return result.toString();
}

From source file:com.jwm123.loggly.reporter.ReportMailer.java

public void send() throws MessagingException {
    if (StringUtils.isNotBlank(config.getMailServer()) && recipients.length > 0) {
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.smtp.port", config.getMailPort().toString());
        props.setProperty("mail.smtp.host", config.getMailServer());
        if (StringUtils.isNotBlank(config.getMailUsername())
                && StringUtils.isNotBlank(config.getMailPassword())) {
            props.setProperty("mail.smtp.user", config.getMailUsername());
            props.setProperty("mail.smtp.password", config.getMailPassword());
        }/* w  w  w .ja v  a2  s .c o m*/

        Session session = Session.getDefaultInstance(props);

        MimeMessage message = new MimeMessage(session);
        message.addFrom(new Address[] { new InternetAddress(config.getMailFrom()) });
        message.setSubject(subject);
        for (String recipient : recipients) {
            message.addRecipient(RecipientType.TO, new InternetAddress(recipient));
        }

        MimeMultipart containingMultipart = new MimeMultipart("mixed");

        MimeMultipart messageMultipart = new MimeMultipart("alternative");
        containingMultipart.addBodyPart(newMultipartBodyPart(messageMultipart));

        messageMultipart.addBodyPart(newTextBodyPart(getText()));

        MimeMultipart htmlMultipart = new MimeMultipart("related");
        htmlMultipart.addBodyPart(newHtmlBodyPart(getHtml()));
        messageMultipart.addBodyPart(newMultipartBodyPart(htmlMultipart));

        containingMultipart.addBodyPart(addReportAttachment());

        message.setContent(containingMultipart);

        Transport.send(message);
    }
}

From source file:org.tsm.concharto.service.EmailService.java

/**
 *
 * @param subject// ww w.  j a v  a2  s  . c o m
 * @param body
 * @param sender
 * @param recipients
 */
public void SendIndividualMessages(String subject, String body, InternetAddress sender, String[] recipients) {
    int emailErrorCount = 0;
    for (int i = 0; i < recipients.length; i++) {
        String recipientEmailAddress = recipients[i];
        MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));
        try {
            message.setText(body);
            message.setSubject(subject);
            message.setFrom(sender);
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipientEmailAddress));
            sendMessage(message);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            emailErrorCount++;
        }
    }
    if (emailErrorCount > 0) {
        String message = emailErrorCount + " out of " + recipients.length + " emails could not be sent.";
        log.error(message);
    }
}

From source file:org.mobicents.servlet.restcomm.email.EmailService.java

EmailResponse send(final Mail mail) {
    try {//  w  ww  . j a va2s .  com
        InternetAddress from;
        if (mail.from() != null || !mail.from().equalsIgnoreCase("")) {
            from = new InternetAddress(mail.from());
        } else {
            from = new InternetAddress(user);
        }
        final InternetAddress to = new InternetAddress(mail.to());
        final MimeMessage email = new MimeMessage(session);
        email.setFrom(from);
        email.addRecipient(Message.RecipientType.TO, to);
        email.setSubject(mail.subject());
        email.setText(mail.body());
        email.addRecipients(Message.RecipientType.CC, InternetAddress.parse(mail.cc(), false));
        email.addRecipients(Message.RecipientType.BCC, InternetAddress.parse(mail.bcc(), false));
        Transport.send(email);
        return new EmailResponse(mail);
    } catch (final MessagingException exception) {
        logger.error(exception.getMessage(), exception);
        return new EmailResponse(exception, exception.getMessage());
    }
}