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.warsaw.data.controller.LoginController.java

private Message buildEmail(Session session, String to) throws Exception {
    Message message = new MimeMessage(session);

    message.setFrom(new InternetAddress(EMAIL));

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

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

    // This mail has 2 part, the BODY and the embedded image
    MimeMultipart multipart = new MimeMultipart("related");

    // first part (the html)
    BodyPart messageBodyPart = new MimeBodyPart();
    String htmlText = "<img style='width:800px' src=\"cid:image1\"><br/>" + "Dzie dobry,<br/><br/>"
            + "witamy na portalu TrasyPoWarszawsku.pl, na ktrym zostalo "
            + "zaoone konto<br/> dla osoby o danych: Jan Marian Ptak. W celu zakoczenia procesu tworzenia "
            + "konta prosimy uy linku aktywacyjnego:<br/><br/>"
            + "<a href='https://test.puesc.gov.pl?link=Gkhh&%JK.'>https://test.puesc.gov.pl?link=Gkhh&%JK.</a><br/><br/>"
            + "Na wywietlonym ekranie prosz wprowadzi zdefiniowane przez siebie haso awaryjne. Po prawidowym"
            + " wprowadzeniu danych<br/> oraz  ustawieniu nowego  hasa dostpowego  konto  na portalu PUESC zostanie aktywowane.<br/>"
            + "Link aktywacyjny pozostanie wany przez 24 godziny od momentu  otrzymania niniejszej wiadomoci.<br/><br/>"
            + "<img style='width:800px' src=\"cid:image2\"><br/><br/>" + "Z powaaniem<br/><br/>"
            + "Zesp portalu PUESC<br/>" + "puesc@mofnet.gov.pl<br/>"
            + "<a href='http://puesc.gov.pl'>http://puesc.gov.pl</a>";

    messageBodyPart.setContent(htmlText, "text/html; charset=ISO-8859-2");
    // add it//from   www. j  av a2  s . c o  m
    multipart.addBodyPart(messageBodyPart);

    // second part (the image)
    messageBodyPart = new MimeBodyPart();
    DataSource fds = new FileDataSource("C:\\Users\\Pawel\\Desktop\\header.png");

    messageBodyPart.setDataHandler(new DataHandler(fds));
    messageBodyPart.setHeader("Content-ID", "<image1>");

    // add image to the multipart
    multipart.addBodyPart(messageBodyPart);

    messageBodyPart = new MimeBodyPart();
    //  URL url = new URL("http://ns3342351.ovh.net:8080/seap_lf_graphicsLayout_theme/images/refresh.png");
    // URLDataSource fds1 =new URLDataSource(url);
    messageBodyPart.setDataHandler(new DataHandler(fds));
    messageBodyPart.setHeader("Content-ID", "<image2>");
    multipart.addBodyPart(messageBodyPart);

    // put everything together
    message.setContent(multipart);

    ByteArrayOutputStream b = new ByteArrayOutputStream();
    try {
        message.writeTo(b);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return message;
}

From source file:domain.Employee.java

private String newPassword(String email) {

    if (email.equals("")) {
        throw new IllegalArgumentException("email must not be null");
    }//w w  w  .j a va 2  s . com
    String pass = RandomStringUtils.randomAlphanumeric(8);
    //email the employee the password they can use to login

    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    String messagebody = String.format(
            "Dear %s %n" + "%n" + "Your account is now ready to login and submit availibility at URL %n" + "%n"
                    + "login: %s %n" + "password: %s %n" + "%n" + "Regards," + "Administration",
            getName(), getEmail(), pass);
    try {
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress("admin@poised-resource-99801.appspotmail.com", "Administration"));
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(getEmail(), getName()));
        msg.setSubject("Your account has been activated");
        msg.setText(messagebody);
        Transport.send(msg);
    } catch (MessagingException | UnsupportedEncodingException ex) {
        Logger.getLogger(Employee.class.getName()).log(Level.SEVERE, null, ex);
    }
    //hash the string and set the employee's password to the hashed one. USED SHA256
    System.out.println(pass);
    String hash = DigestUtils.sha256Hex(pass);
    return hash;
}

From source file:org.jkcsoft.java.mail.Emailer.java

/**
 * The final funnel point method that actually uses Java Mail (javax.mail.*)
 * API to send the message./*from  w  ww .  j a  va  2 s .  c o  m*/
 *
 * @throws MessagingException
 */
private void _sendMsg(InternetAddress[] to, InternetAddress[] bccList, InternetAddress from, String subject,
        String msgBody, String strMimeType) throws MessagingException {
    if (Strings.isEmpty(msgBody)) {
        msgBody = "(no email body; see subject)";
    }
    Session session = Session.getDefaultInstance(javaMailProps, null);
    Message msg = new MimeMessage(session);
    msg.setRecipients(Message.RecipientType.TO, to);
    if (bccList != null) {
        msg.setRecipients(Message.RecipientType.BCC, bccList);
    }
    msg.setFrom(from);
    msg.setSubject(subject);
    msg.setSentDate(new Date());
    msg.setContent(msgBody, strMimeType);
    boolean doTrySend = true;
    int numTries = 0;
    while (doTrySend) {
        numTries++;
        try {
            Transport.send(msg);
            log.info("Sent email; subject=" + subject + " to " + to[0].getAddress() + " ");
            doTrySend = false;
        } catch (MessagingException me) {
            log.warn("Try " + numTries + " of " + MAXTRIES + " failed:", me);
            if (numTries == MAXTRIES) {
                log.error("Failed to send email", me);
                throw me;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e1) {
                LogHelper.error(this, "Retry sleep interrupted", e1);
            }
            doTrySend = numTries < MAXTRIES;
        }
    }
}

From source file:io.uengine.mail.MailAsyncService.java

@Async
public void sendBySmtp(String subject, String text, String fromUser, String fromName, final String toUser,
        String telephone, InternetAddress[] toCC) {
    Session session = setMailProperties(toUser);

    Map<String, Object> model = new HashMap<>();
    model.put("subject", subject);
    model.put("message", text);
    model.put("name", fromName);
    model.put("email", fromUser);
    model.put("telephone", telephone);

    String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "mail/contactus.vm", "UTF-8",
            model);/* www  . jav a  2  s  .c  o m*/
    try {
        InternetAddress from = new InternetAddress(fromUser, fromName);
        Message message = new MimeMessage(session);
        message.setFrom(from);
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toUser));
        message.setSubject(subject);
        //            message.setText(text);
        message.setContent(body, "text/html;charset=utf-8");
        if (toCC != null && toCC.length > 0)
            message.setRecipients(Message.RecipientType.CC, toCC);

        Transport.send(message);

        logger.info("{} ? ?? .", toUser);
    } catch (Exception e) {
        throw new ServiceException("??   .", e);
    }
}

From source file:it.infn.ct.security.actions.ExtendAccount.java

private void sendMail() throws MailException {
    javax.mail.Session session = null;/*  w  w  w. java 2s .  c om*/
    try {
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        session = (javax.mail.Session) envCtx.lookup("mail/Users");

    } catch (Exception ex) {
        _log.error("Mail resource lookup error");
        _log.error(ex.getMessage());
        throw new MailException("Mail Resource not available");
    }

    Message mailMsg = new MimeMessage(session);
    try {
        mailMsg.setFrom(new InternetAddress(mailFrom, mailFrom));

        InternetAddress mailTos[] = new InternetAddress[1];
        mailTos[0] = new InternetAddress(mailTo);
        mailMsg.setRecipients(Message.RecipientType.TO, mailTos);

        mailMsg.setSubject(mailSubject);

        LDAPUser user = LDAPUtils.getUser(username);

        mailBody = mailBody.replaceAll("_USER_", user.getTitle() + " " + user.getGivenname() + " "
                + user.getSurname() + " (" + user.getUsername() + ")");

        mailMsg.setText(mailBody);

        Transport.send(mailMsg);

    } catch (UnsupportedEncodingException ex) {
        _log.error(ex);
        throw new MailException("Mail address format not valid");
    } catch (MessagingException ex) {
        _log.error(ex);
        throw new MailException("Mail message has problems");
    }

}

From source file:it.infn.ct.security.actions.ReactivateUser.java

private void sendMail(LDAPUser user) throws MailException {
    javax.mail.Session session = null;/*from w  ww.  j a va2s. c  o m*/
    try {
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        session = (javax.mail.Session) envCtx.lookup("mail/Users");

    } catch (Exception ex) {
        _log.error("Mail resource lookup error");
        _log.error(ex.getMessage());
        throw new MailException("Mail Resource not available");
    }

    Message mailMsg = new MimeMessage(session);
    try {
        mailMsg.setFrom(new InternetAddress(mailFrom, mailFrom));

        InternetAddress mailTos[] = new InternetAddress[1];
        mailTos[0] = new InternetAddress(mailTo);
        mailMsg.setRecipients(Message.RecipientType.TO, mailTos);

        mailMsg.setSubject(mailSubject);

        mailBody = mailBody.replaceAll("_USER_", user.getTitle() + " " + user.getGivenname() + " "
                + user.getSurname() + " (" + user.getUsername() + ")");

        mailMsg.setText(mailBody);

        Transport.send(mailMsg);

    } catch (UnsupportedEncodingException ex) {
        _log.error(ex);
        throw new MailException("Mail address format not valid");
    } catch (MessagingException ex) {
        _log.error(ex);
        throw new MailException("Mail message has problems");
    }

}

From source file:org.blue.star.plugins.send_mail.java

public boolean execute_check() {

    Properties props = System.getProperties();
    props.put("mail.smtp.host", smtpServer);
    if (smtpAuth) {
        props.put("mail.smtp.auth", "true");
    }//from w w  w.  j a va2 s. c  o  m

    Session session = Session.getInstance(props, null);
    SMTPTransport transport = null;
    //      if (debug)
    //         session.setDebug(true);

    // construct the message
    try {
        Message msg = new MimeMessage(session);
        if (from != null)
            msg.setFrom(new InternetAddress(from));
        else
            msg.setFrom();

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));

        if (subject != null)
            msg.setSubject(subject);

        msg.setHeader("X-Mailer", "blue-send-mail");
        msg.setSentDate(new Date());
        msg.setText(message.replace("\\n", "\n").replace("\\t", "\t"));

        transport = (SMTPTransport) session.getTransport(ssl ? "smtps" : "smtp");
        if (smtpAuth)
            transport.connect(smtpServer, smtpUser, smtpPass);
        else
            transport.connect();
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();

    } catch (MessagingException mE) {
        mE.printStackTrace();
        this.state = common_h.STATE_CRITICAL;
        this.text = mE.getMessage();
        return false;
    } finally {
        try {
            transport.close();
        } catch (Exception e) {
        }
    }

    state = common_h.STATE_OK;
    text = "Message Sent!";
    return true;
}

From source file:org.alfresco.tutorial.repoaction.SendAsEmailActionExecuter.java

@Override
protected void executeImpl(Action action, NodeRef actionedUponNodeRef) {
    if (serviceRegistry.getNodeService().exists(actionedUponNodeRef) == true) {
        // Get the email properties entered via Share Form
        String to = (String) action.getParameterValue(PARAM_EMAIL_TO_NAME);
        String subject = (String) action.getParameterValue(PARAM_EMAIL_SUBJECT_NAME);
        String body = (String) action.getParameterValue(PARAM_EMAIL_BODY_NAME);

        // Get document filename
        Serializable filename = serviceRegistry.getNodeService().getProperty(actionedUponNodeRef,
                ContentModel.PROP_NAME);
        if (filename == null) {
            throw new AlfrescoRuntimeException("Document filename is null");
        }//  w  w w.j a v a2s .  co m
        String documentName = (String) filename;

        try {
            // Create mail session
            Properties mailServerProperties = new Properties();
            mailServerProperties = System.getProperties();
            mailServerProperties.put("mail.smtp.host", "localhost");
            mailServerProperties.put("mail.smtp.port", "2525");
            Session session = Session.getDefaultInstance(mailServerProperties, null);
            session.setDebug(false);

            // Define message
            Message message = new MimeMessage(session);
            String fromAddress = "training@alfresco.com";
            message.setFrom(new InternetAddress(fromAddress));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject(subject);

            // Create the message part with body text
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(body);
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);

            // Create the Attachment part
            //
            //  Get the document content bytes
            byte[] documentData = getDocumentContentBytes(actionedUponNodeRef, documentName);
            if (documentData == null) {
                throw new AlfrescoRuntimeException("Document content is null");
            }
            //  Attach document
            messageBodyPart = new MimeBodyPart();
            messageBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(documentData,
                    new MimetypesFileTypeMap().getContentType(documentName))));
            messageBodyPart.setFileName(documentName);
            multipart.addBodyPart(messageBodyPart);

            // Put parts in message
            message.setContent(multipart);

            // Send mail
            Transport.send(message);

            // Set status on node as "sent via email"
            Map<QName, Serializable> properties = new HashMap<QName, Serializable>();
            properties.put(ContentModel.PROP_ORIGINATOR, fromAddress);
            properties.put(ContentModel.PROP_ADDRESSEE, to);
            properties.put(ContentModel.PROP_SUBJECT, subject);
            properties.put(ContentModel.PROP_SENTDATE, new Date());
            serviceRegistry.getNodeService().addAspect(actionedUponNodeRef, ContentModel.ASPECT_EMAILED,
                    properties);
        } catch (MessagingException me) {
            me.printStackTrace();
            throw new AlfrescoRuntimeException("Could not send email: " + me.getMessage());
        }
    }
}

From source file:pt.ist.fenixedu.integration.task.exportData.parking.ExportCarParkUsers.java

private void sendParkingInfoToRemoteCarPark(String filename, byte[] byteArray)
        throws AddressException, MessagingException {
    final Properties properties = new Properties();
    properties.put("mail.smtp.host", FenixEduAcademicConfiguration.getConfiguration().getMailSmtpHost());
    properties.put("mail.smtp.name", FenixEduAcademicConfiguration.getConfiguration().getMailSmtpName());
    properties.put("mailSender.max.recipients",
            FenixEduAcademicConfiguration.getConfiguration().getMailSenderMaxRecipients());
    properties.put("mail.debug", "false");
    final Session session = Session.getDefaultInstance(properties, null);

    final Sender sender = Bennu.getInstance().getSystemSender();

    final Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(sender.getFromAddress()));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(EMAIL_ADDRESSES_TO_SEND_DATA));
    message.setSubject("Utentes IST - Atualizao");
    message.setText("Listagem atualizada de utentes do IST: " + new DateTime().toString("yyyy-MM-dd HH:mm"));

    MimeBodyPart messageBodyPart = new MimeBodyPart();

    Multipart multipart = new MimeMultipart();

    messageBodyPart = new MimeBodyPart();
    DataSource source = new ByteArrayDataSource(byteArray, "text/plain");
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(filename);
    multipart.addBodyPart(messageBodyPart);

    message.setContent(multipart);/*from  w w w . ja v  a 2 s  .  c o m*/

    Transport.send(message);
}

From source file:org.artifactory.mail.MailServiceImpl.java

/**
 * Send an e-mail message/*from   www  .jav  a 2  s  .  c om*/
 *
 * @param recipients Recipients of the message that will be sent
 * @param subject    The subject of the message
 * @param body       The body of the message
 * @param config     A mail server configuration to use
 * @throws Exception
 */
@Override
public void sendMail(String[] recipients, String subject, String body, final MailServerConfiguration config)
        throws EmailException {

    verifyParameters(recipients, config);

    if (!config.isEnabled()) {
        log.debug("Ignoring requested mail delivery. The given configuration is disabled.");
        return;
    }

    boolean debugEnabled = log.isDebugEnabled();

    Properties properties = new Properties();

    properties.put("mail.smtp.host", config.getHost());
    properties.put("mail.smtp.port", Integer.toString(config.getPort()));

    properties.put("mail.smtp.quitwait", "false");

    //Default protocol
    String protocol = "smtp";

    //Enable TLS if set
    if (config.isUseTls()) {
        properties.put("mail.smtp.starttls.enable", "true");
    }

    //Enable SSL if set
    boolean useSsl = config.isUseSsl();
    if (useSsl) {
        properties.put("mail.smtp.socketFactory.port", Integer.toString(config.getPort()));
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.put("mail.smtp.socketFactory.fallback", "false");
        //Requires special protocol
        protocol = "smtps";
    }

    //Set debug property if enabled by the logger
    properties.put("mail.debug", debugEnabled);

    Authenticator authenticator = null;
    if (!StringUtils.isEmpty(config.getUsername())) {
        properties.put("mail.smtp.auth", "true");
        authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(config.getUsername(), config.getPassword());
            }
        };
    }

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

    String subjectPrefix = config.getSubjectPrefix();
    String fullSubject = (!StringUtils.isEmpty(subjectPrefix)) ? (subjectPrefix + " " + subject) : subject;
    try {
        message.setSubject(fullSubject);

        if (!StringUtils.isEmpty(config.getFrom())) {
            InternetAddress addressFrom = new InternetAddress(config.getFrom());
            message.setFrom(addressFrom);
        }

        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        message.addRecipients(Message.RecipientType.TO, addressTo);

        //Create multi-part message in case we want to add html support
        Multipart multipart = new MimeMultipart("related");

        BodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(body, "text/html");
        multipart.addBodyPart(htmlPart);
        message.setContent(multipart);

        //Set debug property if enabled by the logger
        session.setDebug(debugEnabled);

        //Connect and send
        Transport transport = session.getTransport(protocol);
        if (useSsl) {
            transport.connect(config.getHost(), config.getPort(), config.getUsername(), config.getPassword());
        } else {
            transport.connect();
        }
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    } catch (MessagingException e) {
        String em = e.getMessage();
        throw new EmailException(
                "An error has occurred while sending an e-mail" + (em != null ? ": " + em.trim() : "") + ".\n",
                e);
    }
}