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:com.email.SendEmailCrashReport.java

/**
 * Sends crash email to predetermined list from the database.
 *
 * Also BCCs members of XLN team for notification of errors
 *///from   w  ww  . ja  v  a  2 s .c o m
public static void sendCrashEmail() {
    //Get Account
    SystemEmailModel account = null;
    for (SystemEmailModel acc : Global.getSystemEmailParams()) {
        if (acc.getSection().equals("ERROR")) {
            account = acc;
            break;
        }
    }

    if (account != null) {
        String FROMaddress = account.getEmailAddress();
        List<String> TOAddresses = SystemErrorEmailList.getActiveEmailAddresses();
        String[] BCCAddressess = ("Anthony.Perk@XLNSystems.com".split(";"));
        String subject = "SERB 3.0 Application Daily Error Report for "
                + Global.getMmddyyyy().format(Calendar.getInstance().getTime());
        String body = buildBody();

        Authenticator auth = EmailAuthenticator.setEmailAuthenticator(account);
        Properties properties = EmailProperties.setEmailOutProperties(account);

        Session session = Session.getInstance(properties, auth);
        MimeMessage email = new MimeMessage(session);

        try {
            for (String TO : TOAddresses) {
                if (EmailValidator.getInstance().isValid(TO)) {
                    email.addRecipient(Message.RecipientType.TO, new InternetAddress(TO));
                }
            }

            for (String BCC : BCCAddressess) {
                if (EmailValidator.getInstance().isValid(BCC)) {
                    email.addRecipient(Message.RecipientType.BCC, new InternetAddress(BCC));
                }
            }

            email.setFrom(new InternetAddress(FROMaddress));
            email.setSubject(subject);
            email.setText(body);
            Transport.send(email);
        } catch (AddressException ex) {
            ExceptionHandler.Handle(ex);
        } catch (MessagingException ex) {
            ExceptionHandler.Handle(ex);
        }
    } else {
        System.out.println("No account found to send Error Email");
    }
}

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));
    }/*  ww w  .ja va 2  s. 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:network.thunder.server.etc.Tools.java

public static void emailException(Exception e, Message m, Channel c, Payment p, Transaction channelTransaction,
        Transaction t) {/*from  ww w. j  av  a2 s .c o m*/
    String to = "matsjj@gmail.com";
    String from = "exception@thunder.network";
    String host = "localhost";
    Properties properties = System.getProperties();
    properties.setProperty("mail.smtp.host", host);
    Session session = Session.getDefaultInstance(properties);

    try {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));

        message.setSubject("New Critical Exception thrown..");

        String text = "";

        text += Tools.stacktraceToString(e);
        text += "\n";
        if (m != null) {
            text += m;
        }
        text += "\n";
        if (c != null) {
            text += c;
        }
        text += "\n";
        if (p != null) {
            text += p;
        }
        text += "\n";
        if (channelTransaction != null) {
            text += channelTransaction;
        }
        text += "\n";
        if (t != null) {
            text += t;
        }

        // Now set the actual message
        message.setText(text);

        // Send message
        Transport.send(message);
        System.out.println("Sent message successfully....");
    } catch (MessagingException mex) {
        //           mex.printStackTrace();
    }
}

From source file:com.iana.boesc.utility.BOESCUtil.java

public static boolean sendEmailWithAttachments(final String emailFrom, final String subject,
        final InternetAddress[] addressesTo, final String body, final File attachment) {
    try {// w w  w .j  av  a 2  s . c om
        Session session = Session.getInstance(GlobalVariables.EMAIL_PROPS, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("", "");
            }
        });

        MimeMessage message = new MimeMessage(session);

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

        // Set To: header field of the header.
        message.addRecipients(Message.RecipientType.TO, addressesTo);

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

        // Create the message part
        BodyPart messageBodyPart = new javax.mail.internet.MimeBodyPart();

        // Fill the message
        messageBodyPart.setText(body);
        messageBodyPart.setContent(body, "text/html");

        // Create a multi part message
        Multipart multipart = new javax.mail.internet.MimeMultipart();

        // Set text message part
        multipart.addBodyPart(messageBodyPart);

        // Part two is attachment
        messageBodyPart = new javax.mail.internet.MimeBodyPart();

        DataSource source = new FileDataSource(attachment);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(attachment.getName());
        multipart.addBodyPart(messageBodyPart);

        // Send the complete message parts
        message.setContent(multipart);
        // Send message
        Transport.send(message);

        return true;
    } catch (Exception ex) {
        ex.getMessage();
        return false;
    }
}

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//from  w w w . j av a  2  s . co 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:com.emc.kibana.emailer.KibanaEmailer.java

private static void sendFileEmail(String security) {

    final String username = smtpUsername;
    final String password = smtpPassword;

    // Get system properties
    Properties properties = System.getProperties();

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

    if (security.equals(SMTP_SECURITY_TLS)) {
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.host", smtpHost);
        properties.put("mail.smtp.port", smtpPort);
    } else if (security.equals(SMTP_SECURITY_SSL)) {
        properties.put("mail.smtp.socketFactory.port", smtpPort);
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.port", smtpPort);
    }/*from w  ww.  j  a  v a2 s.c o m*/

    Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });

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

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

        // Set To: header field of the header.
        for (String destinationAddress : destinationAddressList) {
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(destinationAddress));
        }

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

        // Create the message part 
        BodyPart messageBodyPart = new MimeBodyPart();

        StringBuffer bodyBuffer = new StringBuffer(mailBody);
        if (!kibanaUrls.isEmpty()) {
            bodyBuffer.append("\n\n");
        }

        // Add urls info to e-mail
        for (Map<String, String> kibanaUrl : kibanaUrls) {
            // Add urls to e-mail
            String urlName = kibanaUrl.get(NAME_KEY);
            String reportUrl = kibanaUrl.get(URL_KEY);
            if (urlName != null && reportUrl != null) {
                bodyBuffer.append("- ").append(urlName).append(": ").append(reportUrl).append("\n\n\n");
            }
        }

        // Fill the message
        messageBodyPart.setText(bodyBuffer.toString());

        // Create a multipart message
        Multipart multipart = new MimeMultipart();

        // Set text message part
        multipart.addBodyPart(messageBodyPart);

        // Part two is attachments
        for (Map<String, String> kibanaScreenCapture : kibanaScreenCaptures) {
            messageBodyPart = new MimeBodyPart();
            String absoluteFilename = kibanaScreenCapture.get(ABSOLUE_FILE_NAME_KEY);
            String filename = kibanaScreenCapture.get(FILE_NAME_KEY);
            DataSource source = new FileDataSource(absoluteFilename);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(filename);

            multipart.addBodyPart(messageBodyPart);
        }

        // Send the complete message parts
        message.setContent(multipart);

        // Send message
        Transport.send(message);
        logger.info("Sent mail message successfully");
    } catch (MessagingException mex) {
        throw new RuntimeException(mex);
    }
}

From source file:de.hybris.platform.cuppytrail.forgotpassword.actions.SendEmailAction.java

@Override
public void executeAction(final ForgotPasswordProcessModel process) throws RetryLaterException, Exception {
    final EmailMessageModel emailMessage = process.getEmailMessage();
    final MimeMessagePreparator preparator = new MimeMessagePreparator() {

        @Override/*  w  w w.  j ava2s  . c om*/
        public void prepare(final MimeMessage message) throws Exception {
            message.setSubject(emailMessage.getSubject());
            message.setText(emailMessage.getBody());
            message.setRecipients(RecipientType.TO, emailMessage.getRecipientAddress());
        }

    };
    mailSender.send(preparator);
}

From source file:net.indialend.attendance.compnent.Email.java

/**
 * This method triggers the email in background thread i.e. the mail is sent
 * asynchronously//from w  ww .j ava 2 s. c om
 *
 * @param from Email from which mail is triggered
 * @param to Email to whom mail has to be sent
 * @param subject Subject of the email Messages
 * @param msg Message body to be sent along with email
 * @throws InterruptedException
 */
@Async
public void sendMail(String from, String to, String subject, String msg) throws InterruptedException {
    try {

        MimeMessage message = mailSender.createMimeMessage();
        message.setSubject(subject);
        message.setHeader("Content-Type", "text/plain; charset=UTF-8");
        MimeMessageHelper helper;
        helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setText(msg, true);
        mailSender.send(message);
    } catch (MessagingException ex) {
        ex.printStackTrace();
    }
}

From source file:nz.co.testamation.common.mail.MimeMessageFactoryImpl.java

@Override
public Message create(Email email) {
    try {//w  w w  .j  a v  a2 s .c  o m
        EmailAddresses emailAddresses = email.getEmailAddresses();

        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setSubject(email.getSubject());
        mimeMessage.setFrom(new InternetAddress(emailAddresses.getFrom()));

        if (StringUtils.isNotBlank(emailAddresses.getReplyTo())) {
            mimeMessage.setReplyTo(InternetAddress.parse(emailAddresses.getReplyTo()));
        }

        addRecipients(mimeMessage, Message.RecipientType.TO, emailAddresses.getToAddresses());
        addRecipients(mimeMessage, Message.RecipientType.CC, emailAddresses.getCcAddresses());
        addRecipients(mimeMessage, Message.RecipientType.BCC, emailAddresses.getBccAddresses());

        mimeMessage.setContent(multipartMessageFactory.create(email));
        mimeMessage.setSentDate(new Date());

        return mimeMessage;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}

From source file:com.local.ask.controller.mail.MailManagerImpl.java

@Override
public void confirmRegistration(UserTemp userTemp) {

    try {//w ww  . j  a va 2s . c o m

        MimeMessage message = mailSender.createMimeMessage();

        message.setSubject("Local Ask - Confirm Registration");
        message.setFrom(new InternetAddress("local.ask.com@gmail.com"));

        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setTo(userTemp.getEmail());
        String text;
        text = template.replace("{displayName}", userTemp.getDisplayName())
                .replace("{email}", userTemp.getEmail()).replace("{id}", userTemp.getConfirmCode());

        helper.setText(text, true);

        mailSender.send(message);

    } catch (MessagingException ex) {
        Logger.getLogger(MailManagerImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
}