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:AmazonSESSample.java

private static RawMessage getRawMessage() throws MessagingException, IOException {
    // JavaMail representation of the message
    Session s = Session.getInstance(new Properties(), null);
    s.setDebug(true);//from w  ww .java  2s.c  o m
    MimeMessage msg = new MimeMessage(s);

    // Sender and recipient
    msg.setFrom(new InternetAddress("aravind@gofastpay.com"));
    InternetAddress[] address = { new InternetAddress("aravind@gofastpay.com") };
    msg.setRecipients(javax.mail.Message.RecipientType.TO, address);
    msg.setSentDate(new Date());
    // Subject
    msg.setSubject(SUBJECT);

    // Add a MIME part to the message
    //MimeMultipart mp = new MimeMultipart();
    Multipart mp = new MimeMultipart();
    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    //mimeBodyPart.setText(BODY);

    //BodyPart part = new MimeBodyPart();
    //String myText = BODY;
    //part.setContent(URLEncoder.encode(myText, "US-ASCII"), "text/html");
    //part.setText(BODY);
    //mp.addBodyPart(part);
    //msg.setContent(mp);
    mimeBodyPart.setContent(BODY, "text/html");
    mp.addBodyPart(mimeBodyPart);
    msg.setContent(mp);

    // Print the raw email content on the console
    //PrintStream out = System.out;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    msg.writeTo(out);
    //String rawString = out.toString();
    //byte[] bytes = IOUtils.toByteArray(msg.getInputStream());
    //ByteBuffer byteBuffer = ByteBuffer.allocate(bytes.length);
    //ByteBuffer byteBuffer = ByteBuffer.wrap(Base64.getEncoder().encode(rawString.getBytes()));

    //byteBuffer.put(bytes);
    //byteBuffer.put(Base64.getEncoder().encode(bytes));
    RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(out.toByteArray()));
    return rawMessage;
}

From source file:com.email.SendEmailNotification.java

/**
 * This sends a basic notification email that is just pure TEXT. Message is
 * sent from the section gathered/*www.  j av a  2 s .  c  o  m*/
 *
 * @param eml DocketNotificationModel
 */
public static void sendNotificationEmail(DocketNotificationModel eml) {
    //Get Account
    SystemEmailModel account = null;
    for (SystemEmailModel acc : Global.getSystemEmailParams()) {
        if (acc.getSection().equals(eml.getSection())) {
            account = acc;
            break;
        }
    }
    if (account != null) {
        String FROMaddress = account.getEmailAddress();
        String[] TOAddressess = ((eml.getSendTo() == null) ? "".split(";") : eml.getSendTo().split(";"));
        String subject = eml.getMessageSubject();
        String body = eml.getMessageBody();

        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 : TOAddressess) {
                if (EmailValidator.getInstance().isValid(To)) {
                    email.addRecipient(Message.RecipientType.TO, new InternetAddress(To));
                }
            }

            email.setFrom(new InternetAddress(FROMaddress));
            email.setSubject(subject);
            email.setText(body);
            if (Global.isOkToSendEmail()) {
                Transport.send(email);
            } else {
                Audit.addAuditEntry("Notification Not Actually Sent: " + eml.getId() + " - " + subject);
            }

            DocketNotification.deleteEmailEntry(eml.getId());
        } catch (AddressException ex) {
            ExceptionHandler.Handle(ex);
        } catch (MessagingException ex) {
            ExceptionHandler.Handle(ex);
        }
    }
}

From source file:com.sat.common.CustomReport.java

/**
 * Sendmail./*from w  w  w. ja va  2s . co  m*/
 * 
 * @param msg
 *            the msg
 * @throws AddressException
 *             the address exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static void sendmail(String msg) throws AddressException, IOException {

    ConfigFileHandlerManager miscConfigFileHandlerManager = new ConfigFileHandlerManager();
    miscConfigFileHandlerManager.loadPropertiesBasedonPropertyFileName("com.cisco.lms.lms");
    Validate miscValidate = new Validate();

    String from = miscValidate.readsystemvariable("MAIL.FROM");
    String host = miscValidate.readsystemvariable("MAIL.SMTP.HOST");
    String to = miscValidate.readsystemvariable("MAIL.TO");

    String subject = miscValidate.readsystemvariable("MAIL.SUBJECT");
    String personal = miscValidate.readsystemvariable("MAIL.FROM.PERSONAL");

    // Mail to details
    Properties properties = System.getProperties();
    properties.setProperty("mail.smtp.host", host);
    javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties);

    // compose the message
    try {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from, personal));

        message.addRecipients(Message.RecipientType.TO, to);
        message.setSubject(subject);
        Multipart mp = new MimeMultipart();
        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(msg, "text/html");
        mp.addBodyPart(htmlPart);
        message.setContent(mp);
        Transport.send(message);
        System.out.println(msg);
        System.out.println("message sent successfully....");

    } catch (MessagingException mex) {
        mex.printStackTrace();
    } catch (Exception e) {
        System.out.println("\tException in sending mail to configured mailers list");
    }
}

From source file:org.latticesoft.util.resource.MessageUtil.java

public static void sendEmail(String fromAddr, String toAddr, String subject, String body,
        Properties mailConfig) {/*w  w w.j a v  a2s .c  o  m*/
    try {
        //Here, no Authenticator argument is used (it is null).
        //Authenticators are used to prompt the user for user
        //name and password.
        Session session = Session.getDefaultInstance(mailConfig);
        MimeMessage message = new MimeMessage(session);
        //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(fromAddr));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddr));
        message.setSubject(subject);
        message.setText(body);
        Transport.send(message);
    } catch (MessagingException me) {
        if (log.isErrorEnabled()) {
            log.error(me);
        }
    }
}

From source file:frameworkcontentspeed.Utils.SendEmailAtachament.java

public static void SendEmailSephoraFailed(String adresaSephora, String from, String to1, String to2,
        String grupSephora, String subject, String filename) throws FileNotFoundException, IOException {

    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");
    //get Session   
    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(from, "anda.cristea");
        }//www.  ja  v  a  2s  .  co  m
    });
    //compose message    
    try {
        MimeMessage message = new MimeMessage(session);
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to1));

        message.setSubject(subject);
        // message.setText(msg);

        BodyPart messageBodyPart = new MimeBodyPart();

        messageBodyPart.setText("Raport teste automate");

        Multipart multipart = new MimeMultipart();

        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();

        DataSource source = new FileDataSource(filename);

        messageBodyPart.setDataHandler(new DataHandler(source));

        messageBodyPart.setFileName(filename);

        multipart.addBodyPart(messageBodyPart);

        message.setContent(multipart);

        //send message  
        Transport.send(message);

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

}

From source file:frameworkcontentspeed.Utils.SendEmailAtachament.java

public static void SendEmailAnda(String from, String to1, String subject, String filename)
        throws FileNotFoundException, IOException {
    //Get properties object    
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");
    //get Session   
    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(from, "anda.cristea");
        }/*  w w w  .  j  ava 2  s  .c  o  m*/
    });
    //compose message    
    try {
        MimeMessage message = new MimeMessage(session);
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to1));

        message.setSubject(subject);
        // message.setText(msg);

        BodyPart messageBodyPart = new MimeBodyPart();

        messageBodyPart.setText("Raport teste automate");

        Multipart multipart = new MimeMultipart();

        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();

        DataSource source = new FileDataSource(filename);

        messageBodyPart.setDataHandler(new DataHandler(source));

        messageBodyPart.setFileName(filename);

        multipart.addBodyPart(messageBodyPart);

        //message.setContent(multipart);

        StringWriter writer = new StringWriter();
        IOUtils.copy(new FileInputStream(new File(filename)), writer);

        message.setContent(writer.toString(), "text/html");

        //send message  
        Transport.send(message);

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

}

From source file:edu.umich.ctools.sectionsUtilityTool.Friend.java

public static void notifyCurrentUser(String instructorName, String instructorEmail, String inviteEmail) {

    M_log.debug("Friend notifyCurrentUser() called");
    String to = instructorEmail;// w  w w .j a  v  a2  s. c o m
    String from = contactEmail;
    String host = mailHost;

    M_log.info("Setting up mailProps");

    Properties properties = System.getProperties();
    properties.put(MAIL_SMTP_AUTH, "false");
    properties.put(MAIL_SMTP_STARTTLS, "true"); //Put to false, if no https is needed
    properties.put(MAIL_SMTP_HOST, host);
    properties.put(MAIL_DEBUG, "true");

    M_log.debug("Initiating Session for sendMail");
    Session session = Session.getInstance(properties);

    try {

        HashMap<String, String> map = new HashMap<String, String>();

        map.put("<instructor>", instructorName);
        map.put("<friend>", inviteEmail);

        emailMessage = Friend.readFile(requesterEmailFile, StandardCharsets.UTF_8);
        emailMessage = replacePlaceHolders(emailMessage, map);

        M_log.debug("Setting up message for sendMail");
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subjectLine);

        message.setText(emailMessage);

        M_log.info("Sending message");
        Transport.send(message);

        M_log.info("Message sent to " + instructorName);

    } catch (Exception e) {
        M_log.error("notifyCurrentUser exception: " + e.getMessage());
    }
}

From source file:org.intermine.util.MailUtils.java

/**
 * Send an email to an address, supplying the recipient, subject and body.
 *
 * @param to the address to send to/*w  w w . j a v  a2s.c o m*/
 * @param subject The Subject of the email
 * @param body The content of the email
 * @param from the address to send from
 * @param webProperties Common properties for all emails (such as from, authentication)
 * @throws MessagingException if there is a problem creating the email
 */
public static void email(String to, String subject, String body, String from, final Properties webProperties)
        throws MessagingException {
    final String user = webProperties.getProperty("mail.smtp.user");
    String smtpPort = webProperties.getProperty("mail.smtp.port");
    String authFlag = webProperties.getProperty("mail.smtp.auth");
    String starttlsFlag = webProperties.getProperty("mail.smtp.starttls.enable");

    Properties properties = System.getProperties();

    properties.put("mail.smtp.host", webProperties.get("mail.host"));
    properties.put("mail.smtp.user", user);
    // Fix to "javax.mail.MessagingException: 501 Syntactically
    // invalid HELO argument(s)" problem
    // See http://forum.java.sun.com/thread.jspa?threadID=487000&messageID=2280968
    properties.put("mail.smtp.localhost", "localhost");
    if (smtpPort != null) {
        properties.put("mail.smtp.port", smtpPort);
    }
    if (starttlsFlag != null) {
        properties.put("mail.smtp.starttls.enable", starttlsFlag);
    }
    if (authFlag != null) {
        properties.put("mail.smtp.auth", authFlag);
    }

    Session session;
    if (authFlag != null && ("true".equals(authFlag) || "t".equals(authFlag))) {
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                String password = (String) webProperties.get("mail.server.password");
                return new PasswordAuthentication(user, password);
            }
        };
        session = Session.getInstance(properties, authenticator);
    } else {
        session = Session.getInstance(properties);
    }
    MimeMessage message = new MimeMessage(session);
    if (StringUtils.isEmpty(user)) {
        message.setFrom(new InternetAddress(from));
    } else {
        message.setReplyTo(InternetAddress.parse(from, true));
        message.setFrom(new InternetAddress(user));
    }
    message.addRecipient(Message.RecipientType.TO, InternetAddress.parse(to, true)[0]);
    message.setSubject(subject);
    message.setContent(body, "text/plain");
    Transport.send(message);
}

From source file:org.yccheok.jstock.alert.GoogleMail.java

private static MimeMessage createEmail(String to, String cc, String from, String subject, String bodyText)
        throws MessagingException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);
    InternetAddress tAddress = new InternetAddress(to);
    InternetAddress cAddress = Utils.isNullOrEmpty(cc) ? null : new InternetAddress(cc);
    InternetAddress fAddress = new InternetAddress(from);

    email.setFrom(fAddress);//from ww w . j  av a 2 s.  c  o m
    if (cAddress != null) {
        email.addRecipient(javax.mail.Message.RecipientType.CC, cAddress);
    }
    email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress);
    email.setSubject(subject);
    email.setText(bodyText);
    return email;
}

From source file:ru.org.linux.user.RegisterController.java

private static void sendEmail(Template tmpl, String nick, String email, boolean isNew)
        throws MessagingException {
    StringBuilder text = new StringBuilder();

    text.append("?!\n\n");
    if (isNew) {//  w  w w .  j  a v a 2  s .com
        text.append(
                "\t   ? http://www.linux.org.ru/ ?? ?? ?,\n");
    } else {
        text.append(
                "\t   ? http://www.linux.org.ru/   ?? ?,\n");
    }

    text.append("     ? ? (e-mail).\n\n");
    text.append(
            "  ?    ? ? ?: '");
    text.append(nick);
    text.append("'\n\n");
    text.append(
            "?   ,     - ?  ? ?!\n\n");

    if (isNew) {
        text.append(
                "?     ???    ? http://www.linux.org.ru/,\n");
        text.append(
                "  ?  ? ?   ?    ?.\n\n");
    } else {
        text.append(
                "?      ? ? ? http://www.linux.org.ru/,\n");
        text.append("  ?  ? .\n\n");
    }

    String regcode = User.getActivationCode(tmpl.getSecret(), nick, email);

    text.append(
            "?    ?? http://www.linux.org.ru/activate.jsp\n\n");
    text.append(" : ").append(regcode).append("\n\n");
    text.append("  ?!\n");

    Properties props = new Properties();
    props.put("mail.smtp.host", "localhost");
    Session mailSession = Session.getDefaultInstance(props, null);

    MimeMessage emailMessage = new MimeMessage(mailSession);
    emailMessage.setFrom(new InternetAddress("no-reply@linux.org.ru"));

    emailMessage.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(email));
    emailMessage.setSubject("Linux.org.ru registration");
    emailMessage.setSentDate(new Date());
    emailMessage.setText(text.toString(), "UTF-8");

    Transport.send(emailMessage);
}