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:pt.ist.fenix.api.SupportFormResource.java

private void sendEmail(String from, String subject, String body, SupportBean bean) {
    Properties props = new Properties();
    props.put("mail.smtp.host", Objects
            .firstNonNull(FenixEduAcademicConfiguration.getConfiguration().getMailSmtpHost(), "localhost"));
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage message = new MimeMessage(session);
    try {/*from w w  w . j a v a2  s .c  o  m*/
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO,
                new InternetAddress(CoreConfiguration.getConfiguration().defaultSupportEmailAddress()));
        message.setSubject(subject);
        message.setText(body);

        Multipart multipart = new MimeMultipart();
        {
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(body);
            multipart.addBodyPart(messageBodyPart);
        }

        if (!Strings.isNullOrEmpty(bean.attachment)) {
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setDataHandler(new DataHandler(
                    new ByteArrayDataSource(Base64.getDecoder().decode(bean.attachment), bean.mimeType)));
            messageBodyPart.setFileName(bean.fileName);
            multipart.addBodyPart(messageBodyPart);
        }

        message.setContent(multipart);

        Transport.send(message);
    } catch (Exception e) {
        logger.error("Could not send support email! Original message was: " + body, e);
    }
}

From source file:org.trpr.platform.integration.impl.email.SpringMailSender.java

/**
 * Interface method implementation. Sends an email using the specified values and the configured mail sender.
 * @see org.trpr.platform.integration.spi.email.MailSender#sendMail(java.lang.String, java.lang.String[], java.lang.String, java.net.URL)
 */// w w w  . j  a  v a2  s.  c  om
public void sendMail(final String senderAddress, final String subject, final String[] recipients,
        final String message, final URL attachmentURL) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws Exception {
            InternetAddress[] recipientAddresses = new InternetAddress[recipients.length];
            for (int i = 0; i < recipientAddresses.length; i++) {
                recipientAddresses[i] = new InternetAddress(recipients[i]);
            }
            mimeMessage.setRecipients(Message.RecipientType.TO, recipientAddresses);
            mimeMessage.setFrom(new InternetAddress(senderAddress));
            mimeMessage.setSubject(subject);
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); // multi-part flag is set to true for accommodating attachments
            if (attachmentURL != null) {
                helper.addAttachment(attachmentURL.getFile(), new FileSystemResource(attachmentURL.toString()));
            }
            helper.setText(message);
        }
    };
    this.mailSender.send(preparator);
}

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

public void sendMail(MessageConfig config) throws MessagingException {
    log.debug("Sending message " + config);

    Session session = getSession();//from  w w  w.j a  va  2  s  .c  o  m
    final MimeMessage mimeMessage = new MimeMessage(session);
    try {
        mimeMessage.setFrom(new InternetAddress(config.getFrom(), config.getFromName()));
        mimeMessage.addRecipient(Message.RecipientType.TO,
                new InternetAddress(config.getTo(), config.getToName()));
    } catch (UnsupportedEncodingException ex) {
        throw new MessagingException("Setting from or to failed", ex);
    }
    mimeMessage.setSubject(config.getSubject());
    mimeMessage.setContent(config.getContent(), config.getContentType());
    // we don't send in a new Thread so that we get the Exception
    Transport.send(mimeMessage);
}

From source file:cz.filmtit.userspace.Emailer.java

/**
 * Sends an email with parameters that has been collected before in the fields of the class.
 * @return Sign if the email has been successfully sent
 */// w ww .j a va 2 s  .  c  o  m
public boolean send() {
    if (hasCollectedData()) {
        // send mail;
        javax.mail.Session session;
        logger.info("Emailer",
                "Create session for mail login " + (String) configuration.getProperty("mail.filmtit.address")
                        + " password" + (String) configuration.getProperty("mail.filmtit.password"));
        session = javax.mail.Session.getDefaultInstance(configuration, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication((String) configuration.getProperty("mail.filmtit.address"),
                        (String) configuration.getProperty("mail.filmtit.password"));
            }
        });
        session.setDebug(true);
        javax.mail.internet.MimeMessage message = new javax.mail.internet.MimeMessage(session);
        try {
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(this.email));
            message.setFrom(new InternetAddress((String) configuration.getProperty("mail.filmtit.address")));
            message.setSubject(this.subject);
            message.setText(this.message);

            Transport transportSSL = session.getTransport();
            transportSSL.connect((String) configuration.getProperty("mail.smtps.host"),
                    Integer.parseInt(configuration.getProperty("mail.smtps.port")),
                    (String) configuration.getProperty("mail.filmtit.address"),
                    (String) configuration.getProperty("mail.filmtit.password")); // account used
            transportSSL.sendMessage(message, message.getAllRecipients());
            transportSSL.close();
        } catch (MessagingException ex) {
            logger.error("Emailer", "An error while sending an email. " + ex);
        }
        return true;
    }
    logger.warning("Emailer", "Emailer has not collected all data to be able to send an email.");
    return false;
}

From source file:gov.nih.nci.caintegrator.application.mail.SendMail.java

public synchronized void sendMail(String mailTo, String mailCC, String mailBody, String subject)
        throws ValidationException {
    try {/*from   w ww.jav  a  2 s  .  c  om*/
        if (mailTo != null && EmailValidator.getInstance().isValid(mailTo)) {
            //get system properties
            Properties props = System.getProperties();

            String to = mailTo;
            // Set up mail server

            props.put("mail.smtp.host", MailConfig.getInstance(mailProperties).getHost());

            //Get session
            Session session = Session.getDefaultInstance(props, null);

            //Define Message
            MimeMessage message = new MimeMessage(session);
            MailManager mailManager = new MailManager(mailProperties);
            message.setFrom(new InternetAddress(mailManager.formatFromAddress()));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            if ((mailCC != null) && EmailValidator.getInstance().isValid(mailCC))
                message.addRecipient(Message.RecipientType.CC, new InternetAddress(mailCC));
            message.setSubject(subject);
            message.setText(mailBody);

            //Send Message

            Transport.send(message);
        } else {
            throw new ValidationException("Invalid Email Address");
        }
    } catch (Exception e) {
        logger.error("Send Mail error", e);
    } //catch
}

From source file:ee.cyber.licensing.service.MailService.java

public void sendExpirationNearingMail(License license) throws IOException, MessagingException {
    logger.info("1st ===> setup Mail Server Properties");
    Properties mailServerProperties = getProperties();

    final String email = mailServerProperties.getProperty("fromEmail");
    final String password = mailServerProperties.getProperty("password");
    final String host = mailServerProperties.getProperty("mail.smtp.host");
    final String mailTo = mailServerProperties.getProperty("mailTo");

    logger.info("2nd ===> create Authenticator object to pass in Session.getInstance argument");

    Authenticator authentication = new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(email, password);
        }/*from   w  w  w. j ava 2s  .co m*/
    };
    logger.info("Mail Server Properties have been setup successfully");

    logger.info("3rd ===> get Mail Session..");
    Session getMailSession = Session.getInstance(mailServerProperties, authentication);

    logger.info("4th ===> generateAndSendEmail() starts");
    MimeMessage mailMessage = new MimeMessage(getMailSession);

    mailMessage.addHeader("Content-type", "text/html; charset=UTF-8");
    mailMessage.addHeader("format", "flowed");
    mailMessage.addHeader("Content-Transfer-Encoding", "8bit");

    mailMessage.setFrom(new InternetAddress(email, "Licensing service"));
    mailMessage.setSubject("License with id " + license.getId() + " is expiring");
    mailMessage.setSentDate(new Date());
    mailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
    String emailBody = "This is test<br><br> Regards, <br>Licensing team";
    mailMessage.setContent(emailBody, "text/html");

    logger.info("5th ===> Get Session");
    sendMail(email, password, host, getMailSession, mailMessage);

}

From source file:rescustomerservices.GmailQuickstart.java

/**
 * Create a MimeMessage using the parameters provided.
 *
 * @param to Email address of the receiver.
 * @param from Email address of the sender, the mailbox account.
 * @param subject Subject of the email./*  www.ja v  a2  s  .  c o  m*/
 * @param bodyText Body text of the email.
 * @param fileDir Path to the directory containing attachment.
 * @param filename Name of file to be attached.
 * @return MimeMessage to be used to send email.
 * @throws MessagingException
 */
public MimeMessage createEmailWithAttachment(String to, String from, String subject, String bodyText,
        String fileDir, String filename) throws MessagingException, IOException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);
    InternetAddress tAddress = new InternetAddress(to);
    InternetAddress fAddress = new InternetAddress(from);

    email.setFrom(fAddress);
    email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress);
    email.setSubject(subject);

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

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(mimeBodyPart);

    mimeBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(fileDir + filename);

    mimeBodyPart.setDataHandler(new DataHandler(source));
    mimeBodyPart.setFileName(filename);
    String contentType = Files.probeContentType(FileSystems.getDefault().getPath(fileDir, filename));
    mimeBodyPart.setHeader("Content-Type", contentType + "; name=\"" + filename + "\"");
    mimeBodyPart.setHeader("Content-Transfer-Encoding", "base64");

    multipart.addBodyPart(mimeBodyPart);

    email.setContent(multipart);

    return email;
}

From source file:org.eclipse.ecr.automation.core.mail.Mailer.java

/**
 * Send a single email./*from  www .j a va  2 s.c  o m*/
 */
public void sendEmail(String from, String to, String subject, String body) throws MessagingException {
    // Here, no Authenticator argument is used (it is null).
    // Authenticators are used to prompt the user for user
    // name and password.
    MimeMessage message = new MimeMessage(getSession());
    // the "from" address may be set in code, or set in the
    // config file under "mail.from" ; here, the latter style is used
    message.setFrom(new InternetAddress(from));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    message.setSubject(subject);
    message.setText(body);
    Transport.send(message);
}

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  v a2  s  . com
    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:eu.scape_project.planning.application.BugReport.java

/**
 * Method responsible for sending a bug report per mail.
 * //from   w  w  w. j  a  v a  2  s.  co m
 * @param userEmail
 *            email address of the user.
 * @param errorDescription
 *            error description given by the user.
 * @param exception
 *            the exception causing the bug/error.
 * @param requestUri
 *            request URI where the error occurred
 * @param location
 *            the location of the application where the error occurred
 * @param applicationName
 *            application name
 * @param plan
 *            the plan where the exception occurred
 * @throws MailException
 *             if the bug report could not be sent
 */
public void sendBugReport(String userEmail, String errorDescription, Throwable exception, String requestUri,
        String location, String applicationName, Plan plan) 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();
        // Date
        builder.append("Date: ").append(DATE_FORMAT.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");

        // Plan
        if (plan == null) {
            builder.append("No plan available.").append("\n\n");
        } else {
            builder.append("Plan ID: ").append(plan.getPlanProperties().getId()).append("\n");
            builder.append("Plan name: ").append(plan.getPlanProperties().getName()).append("\n\n");
        }

        // Description
        builder.append("Description:\n");
        builder.append(SEPARATOR_LINE);
        builder.append(errorDescription).append("\n");
        builder.append(SEPARATOR_LINE).append("\n");

        // Request URI
        builder.append("Request URI: ").append(requestUri).append("\n\n");

        // Exception
        if (exception == null) {
            builder.append("No exception available.").append("\n");
        } else {
            builder.append("Exception type: ").append(exception.getClass().getCanonicalName()).append("\n");
            builder.append("Exception message: ").append(exception.getMessage()).append("\n");

            StringWriter writer = new StringWriter();
            exception.printStackTrace(new PrintWriter(writer));

            builder.append("Stacktrace:\n");
            builder.append(SEPARATOR_LINE);
            builder.append(writer.toString());
            builder.append(SEPARATOR_LINE);
        }

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

        Transport.send(message);
        log.debug("Bug report mail from user {} sent successfully to {}", user.getUsername(),
                config.getString("mail.feedback"));

        String userMessage = "Bugreport sent. Thank you for your feedback. We will try to analyse and resolve the issue as soon as possible.";
        Notification notification = new Notification(UUID.randomUUID().toString(), new Date(), "PLATO",
                userMessage, user);
        try {
            utx.begin();
            em.persist(notification);
            utx.commit();
        } catch (Exception e) {
            log.error("Failed to store user notification for bugreport of {}", user.getUsername(), e);
        }

    } catch (MessagingException e) {
        throw new MailException("Error sending bug report mail from user " + user.getUsername() + " to "
                + config.getString("mail.feedback"), e);
    }
}