Example usage for javax.mail Message setSubject

List of usage examples for javax.mail Message setSubject

Introduction

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

Prototype

public abstract void setSubject(String subject) throws MessagingException;

Source Link

Document

Set the subject of this message.

Usage

From source file:com.mycompany.craftdemo.utility.java

public static void send(long phno, double price, double profit, String domain, String company) {
    HashMap<String, String> domainMap = new HashMap<>();
    domainMap.put("TMobile", "tmomail.net ");
    domainMap.put("ATT", "txt.att.net");
    domainMap.put("Sprint", "messaging.sprintpcs.com");
    domainMap.put("Verizon", "vtext.com");
    String to = phno + "@" + domainMap.get(domain); //change accordingly

    // Sender's email ID needs to be mentioned
    String from = "uni5prince@gmail.com"; //change accordingly
    final String username = "uni5prince"; //change accordingly
    final String password = "savageph8893"; //change accordingly

    // Assuming you are sending email through relay.jangosmtp.net
    String host = "smtp.gmail.com";

    Properties props = new Properties();
    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");

    // Get the Session object.
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }/*from  w  w w .  ja va  2 s . c o m*/
    });

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

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

        // Set To: header field of the header.
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

        // Set Subject: header field
        message.setSubject("Prices have gone up!!");

        // Now set the actual message
        message.setText("Hello Jane, Stock prices for " + company + " has reached to $" + price
                + " with profit of $" + profit);

        // Send message
        Transport.send(message);

        System.out.println("Sent message successfully....");

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.vulpe.commons.util.VulpeEmailUtil.java

/**
 * Send mail to recipients by Web Service.
 *
 * @param recipients//from w  w w. j a  v a2  s  .c o m
 *
 * @param subject
 *
 * @param body
 *
 * @param mailerService
 *
 * @throws VulpeSystemException
 *             exception
 */
public static void sendMailByService(final String[] recipients, final String subject, final String body,
        final String mailerService) {
    try {
        final ResourceBundle bundle = ResourceBundle.getBundle("mail");
        String mailFrom = "";
        if (bundle.containsKey("mail.from")) {
            mailFrom = bundle.getString("mail.from");
        }
        final InitialContext initialContext = new InitialContext();
        final Session session = (Session) initialContext.lookup(mailerService);
        final Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(mailFrom));
        for (String recipient : recipients) {
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
        }
        // msg.setRecipient(Message.RecipientType.TO, new
        // InternetAddress(to));
        message.setSubject(subject);
        message.setText(body);
        Transport.send(message);
    } catch (Exception e) {
        LOG.error(e.getMessage());
    }

}

From source file:fr.paris.lutece.portal.service.mail.MailUtil.java

/**
 * Common part for sending message process :
 * <ul>/*from  ww  w.j a v  a2 s.  c  o m*/
 * <li>initializes a mail session with the SMTP server</li>
 * <li>activates debugging</li>
 * <li>instantiates and initializes a mime message</li>
 * <li>sets the sent date, the from field, the subject field</li>
 * <li>sets the recipients</li>
 * </ul>
 *
 *
 * @return the message object initialized with the common settings
 * @param strRecipientsTo The list of the main recipients email.Every
 *            recipient must be separated by the mail separator defined in
 *            config.properties
 * @param strRecipientsCc The recipients list of the carbon copies .
 * @param strRecipientsBcc The recipients list of the blind carbon copies .
 * @param strSenderName The sender name.
 * @param strSenderEmail The sender email address.
 * @param strSubject The message subject.
 * @param session The SMTP session object
 * @throws AddressException If invalid address
 * @throws MessagingException If a messaging error occurred
 */
protected static Message prepareMessage(String strRecipientsTo, String strRecipientsCc, String strRecipientsBcc,
        String strSenderName, String strSenderEmail, String strSubject, Session session)
        throws MessagingException, AddressException {
    // Instantiate and initialize a mime message
    Message msg = new MimeMessage(session);
    msg.setSentDate(new Date());

    try {
        msg.setFrom(new InternetAddress(strSenderEmail, strSenderName,
                AppPropertiesService.getProperty(PROPERTY_CHARSET)));
        msg.setSubject(MimeUtility.encodeText(strSubject, AppPropertiesService.getProperty(PROPERTY_CHARSET),
                ENCODING));
    } catch (UnsupportedEncodingException e) {
        throw new AppException(e.toString());
    }

    // Instantiation of the list of address
    if (strRecipientsTo != null) {
        msg.setRecipients(Message.RecipientType.TO, getAllAdressOfRecipients(strRecipientsTo));
    }

    if (strRecipientsCc != null) {
        msg.setRecipients(Message.RecipientType.CC, getAllAdressOfRecipients(strRecipientsCc));
    }

    if (strRecipientsBcc != null) {
        msg.setRecipients(Message.RecipientType.BCC, getAllAdressOfRecipients(strRecipientsBcc));
    }

    return msg;
}

From source file:org.capelin.mvc.mail.SMTPMailSender.java

protected boolean send(String recipient, String body, boolean html) {
    Properties props = System.getProperties();
    props.put("mail.smtp.host", serverName);
    Session session = Session.getInstance(props, null);
    props.put("mail.from", sender);
    Message msg = new MimeMessage(session);
    try {//from   w w  w.j  a  v a 2  s. co m
        msg.setSubject(subject);
        msg.setFrom();
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient, false));
        if (html) {
            msg.setContent(new String(body.getBytes(), "iso-8859-1"), "text/html; charset=iso-8859-1");
        } else {
            msg.setText(body);
        }
        // Send the message:
        Transport.send(msg);
        log.debug("Email send to: " + sender);
        return true;
    } catch (MessagingException e) {
        log.info("Email Sending failed due to " + e);
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return false;
}

From source file:org.apache.oodt.cas.crawl.action.EmailNotification.java

@Override
public boolean performAction(File product, Metadata metadata) throws CrawlerActionException {
    try {/*w  w w.j  ava2s .c o m*/
        Properties props = new Properties();
        props.put("mail.host", this.mailHost);
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.from", this.sender);

        Session session = Session.getDefaultInstance(props);
        Message msg = new MimeMessage(session);
        msg.setSubject(PathUtils.doDynamicReplacement(subject, metadata));
        msg.setText(new String(PathUtils.doDynamicReplacement(message, metadata).getBytes()));
        for (String recipient : recipients) {
            try {
                msg.addRecipient(Message.RecipientType.TO, new InternetAddress(
                        PathUtils.replaceEnvVariables(recipient.trim(), metadata), ignoreInvalidAddresses));
                LOG.fine("Recipient: " + PathUtils.replaceEnvVariables(recipient.trim(), metadata));
            } catch (AddressException ae) {
                LOG.fine("Recipient: " + PathUtils.replaceEnvVariables(recipient.trim(), metadata));
                LOG.warning(ae.getMessage());
            }
        }
        LOG.fine("Subject: " + msg.getSubject());
        LOG.fine("Message: " + new String(PathUtils.doDynamicReplacement(message, metadata).getBytes()));
        Transport.send(msg);
        return true;
    } catch (Exception e) {
        LOG.severe(e.getMessage());
        return false;
    }
}

From source file:uk.ac.ox.it.ords.api.project.services.impl.SendMailTLS.java

protected void sendMail(String subject, String messageText) throws Exception {

    ////from   w ww .  j  av  a2s  .  c o m
    // Validate Mail server settings
    //
    if (!props.containsKey("mail.smtp.username") || !props.containsKey("mail.smtp.password")
            || !props.containsKey("mail.smtp.host")) {
        log.error("Unable to send emails as email server configuration is missing");
        throw new Exception("Unable to send emails as email server configuration is missing");
    }

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(props.get("mail.smtp.username").toString(),
                    props.get("mail.smtp.password").toString());
        }
    });

    try {
        Message message = new MimeMessage(session);
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
        message.setSubject(subject);
        message.setText(messageText);

        Transport.send(message);

        if (log.isDebugEnabled()) {
            log.debug(String.format("Sent email to %s", email));
            log.debug("with content: " + messageText);
        }
    } catch (MessagingException e) {
        log.error("Unable to send email to " + email, e);
        throw new Exception("Unable to send email to " + email, e);
    }
}

From source file:uk.ac.ox.it.ords.api.database.services.impl.SendMailTLS.java

protected void sendMail(String subject, String messageText) throws Exception {

    ////  w ww .  j  a v a  2  s  .c om
    // Validate Mail server settings
    //
    if (!props.containsKey("mail.smtp.username") || !props.containsKey("mail.smtp.password")
            || !props.containsKey("mail.smtp.host")) {
        log.error("Unable to send emails as email server configuration is missing");
        //throw new Exception("Unable to send emails as email server configuration is missing");
        return; // 
    }

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(props.get("mail.smtp.username").toString(),
                    props.get("mail.smtp.password").toString());
        }
    });

    try {
        Message message = new MimeMessage(session);
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
        message.setSubject(subject);
        message.setText(messageText);

        Transport.send(message);

        if (log.isDebugEnabled()) {
            log.debug(String.format("Sent email to %s", email));
            log.debug("with content: " + messageText);
        }
    } catch (MessagingException e) {
        log.error("Unable to send email to " + email, e);
        throw new Exception("Unable to send email to " + email, e);
    }
}

From source file:io.kodokojo.service.SmtpEmailSender.java

@Override
public void send(List<String> to, List<String> cc, List<String> ci, String subject, String content,
        boolean htmlContent) {
    if (CollectionUtils.isEmpty(to)) {
        throw new IllegalArgumentException("to must be defined.");
    }//ww w.j av  a  2s . c  o m
    if (isBlank(content)) {
        throw new IllegalArgumentException("content must be defined.");
    }
    Session session = Session.getDefaultInstance(properties, new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });
    Message message = new MimeMessage(session);
    try {
        message.setFrom(from);
        message.setSubject(subject);
        InternetAddress[] toInternetAddress = convertToInternetAddress(to);
        message.setRecipients(Message.RecipientType.TO, toInternetAddress);
        if (CollectionUtils.isNotEmpty(cc)) {
            InternetAddress[] ccInternetAddress = convertToInternetAddress(cc);
            message.setRecipients(Message.RecipientType.CC, ccInternetAddress);
        }
        if (CollectionUtils.isNotEmpty(ci)) {
            InternetAddress[] ciInternetAddress = convertToInternetAddress(ci);
            message.setRecipients(Message.RecipientType.BCC, ciInternetAddress);
        }
        if (htmlContent) {
            message.setContent(content, "text/html");
        } else {
            message.setText(content);
        }
        message.setHeader("X-Mailer", "Kodo Kojo mailer");
        message.setSentDate(new Date());
        Transport.send(message);

    } catch (MessagingException e) {
        LOGGER.error("Unable to send email to {} with subject '{}'", StringUtils.join(to, ","), subject, e);
    }
}

From source file:uk.ac.ox.it.ords.api.statistics.services.impl.SendMailTLS.java

private void sendMail() {
    if (sendEmails) {
        if (username == null) {
            log.error("Unable to send emails due to null user");
            return;
        }//  w w  w. j  ava 2s.  c om
        Session session = Session.getInstance(props, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(props.get("mail.smtp.username").toString(),
                        props.get("mail.smtp.password").toString());
            }
        });

        try {
            Message message = new MimeMessage(session);
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
            message.setSubject(subject);
            message.setText(messageText);
            message.setFrom(new InternetAddress("ords@it.ox.ac.uk"));

            Transport.send(message);

            if (log.isDebugEnabled()) {
                log.debug(String.format("Sent email to %s (name %s)", email, username));
                log.debug("with content: " + messageText);
            }

        } catch (MessagingException e) {
            log.error("Unable to send email to " + email + " username " + username, e);
        }
    }
}

From source file:pmp.springmail.TestDrive.java

void sendEmailViaPlainMail(String text) {
    Authenticator authenticator = new Authenticator() {

        @Override/*  ww w  .j  a va  2  s. c o  m*/
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(USER, PASS);
        }
    };

    Session session = Session.getInstance(props, authenticator);
    Message message = new MimeMessage(session);

    try {
        message.setFrom(new InternetAddress(FROM));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(TO));
        message.setSubject("Plain JavaMail Test");
        message.setText(DATE_FORMAT.format(new Date()) + " " + text);

        Transport.send(message);

    } catch (Exception e) {
        System.err.println(e.getClass().getSimpleName() + " " + e.getMessage());
    }
}