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.jive.myco.seyren.core.service.notification.EmailNotificationService.java

private MimeMessage createMimeMessage(Email email) throws AddressException, MessagingException {

    MimeMessage mail = mailSender.createMimeMessage();
    InternetAddress senderAddress = new InternetAddress(email.getFrom());
    mail.addRecipient(RecipientType.TO, new InternetAddress(email.getTo()));
    mail.setSender(senderAddress);//w w w.j a va 2s . co m
    mail.setFrom(senderAddress);
    mail.setText(email.getMessage());
    mail.setSubject(email.getSubject());
    mail.addHeader("Content-Type", "text/html; charset=UTF-8");

    return mail;
}

From source file:se.inera.axel.shs.processor.ShsMessageMarshaller.java

public void marshal(ShsMessage shsMessage, OutputStream outputStream) throws IllegalMessageStructureException {
    log.trace("marshal(ShsMessage, OutputStream)");

    MimeMultipart multipart = new MimeMultipart();
    BodyPart bodyPart = new MimeBodyPart();

    try {/*from w  w w .  j ava2  s  .  c  o  m*/

        ShsLabel label = shsMessage.getLabel();
        if (label == null) {
            throw new IllegalMessageStructureException("label not found in shs message");
        }

        Content content = label.getContent();
        if (content == null) {
            throw new IllegalMessageStructureException("label/content not found in shs label");
        } else {
            // we will update this according to our data parts below.
            content.getDataOrCompound().clear();

            String contentId = content.getContentId();
            content.setContentId(contentId.substring(0, Math.min(contentId.length(), MAX_LENGTH_CONTENT_ID)));
        }

        List<DataPart> dataParts = shsMessage.getDataParts();

        if (dataParts.isEmpty()) {
            throw new IllegalMessageStructureException("dataparts not found in message");
        }

        for (DataPart dp : dataParts) {
            Data data = new Data();

            data.setDatapartType(dp.getDataPartType());
            data.setFilename(dp.getFileName());
            if (dp.getContentLength() != null && dp.getContentLength() > 0)
                data.setNoOfBytes("" + dp.getContentLength());
            content.getDataOrCompound().add(data);
        }

        bodyPart.setContent(shsLabelMarshaller.marshal(label), "text/xml; charset=ISO-8859-1");
        bodyPart.setHeader("Content-Transfer-Encoding", "binary");

        multipart.addBodyPart(bodyPart);

        for (DataPart dataPart : dataParts) {

            bodyPart = new MimeBodyPart();

            bodyPart.setDisposition(Part.ATTACHMENT);
            if (StringUtils.isNotBlank(dataPart.getFileName())) {
                bodyPart.setFileName(dataPart.getFileName());
            }

            bodyPart.setDataHandler(dataPart.getDataHandler());

            if (dataPart.getTransferEncoding() != null) {
                bodyPart.addHeader("Content-Transfer-Encoding", dataPart.getTransferEncoding().toLowerCase());
            }
            multipart.addBodyPart(bodyPart);
        }

        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setSubject("SHS Message");
        mimeMessage.addHeader("Content-Transfer-Encoding", "binary");

        mimeMessage.setContent(multipart);
        mimeMessage.saveChanges();

        String ignoreList[] = { "Message-ID" };

        mimeMessage.writeTo(outputStream, ignoreList);
        outputStream.flush();

    } catch (Exception e) {
        if (e instanceof IllegalMessageStructureException) {
            throw (IllegalMessageStructureException) e;
        }
        throw new IllegalMessageStructureException(e);
    }

}

From source file:atd.backend.Register.java

public void sendRegMail(Klant k) throws IOException {
    Properties propMail = new Properties();
    InputStream config = null;//from   ww  w.  j a va 2  s. c om
    config = new URL(CONFIG_URL).openStream();
    propMail.load(config);

    Properties props = new Properties();
    props.put("mail.smtp.host", propMail.getProperty("host"));
    props.put("mail.smtp.port", 465);
    props.put("mail.smtp.ssl.enable", true);
    Session mailSession = Session.getInstance(props);
    try {
        Logger.getLogger("atd.log").info("Stuurt mail naar: " + k.getEmail());
        MimeMessage msg = new MimeMessage(mailSession);
        msg.setFrom(new InternetAddress(propMail.getProperty("email"), propMail.getProperty("mailName")));
        msg.setRecipients(Message.RecipientType.TO, k.getEmail());
        msg.setSubject("Uw account is aangemaakt");
        msg.setSentDate(Calendar.getInstance().getTime());
        msg.setContent("Beste " + k.getNaam() + ", \n\nUw account " + k.getUsername()
                + " is aangemaakt, U kunt inloggen op de <a href='https://atd.plebian.nl'>ATD website</a>\n",
                "text/html; charset=utf-8");
        // TODO: Heeft OAUTH nodig, maarja we zijn al niet erg netjes met
        // wachtwoorden
        Transport.send(msg, propMail.getProperty("email"), propMail.getProperty("password"));
    } catch (Exception e) {
        Logger.getLogger("atd.log").warning("send failed: " + e.getMessage());
    }
}

From source file:eu.scape_project.planning.application.Feedback.java

/**
 * Method responsible for sending feedback per mail.
 * /*from  w  ww.jav  a 2s  .c  o m*/
 * @param userEmail
 *            email address of the user.
 * @param userComments
 *            comments from the user
 * @param location
 *            the location of the application where the error occurred
 * @param applicationName
 *            the name of the application
 * @throws MailException
 *             if the feedback could not be sent
 */
public void sendFeedback(String userEmail, String userComments, String location, String applicationName)
        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();
        builder.append("Date: ").append(dateFormat.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");

        // Comments
        builder.append("Comments:\n");
        builder.append(SEPARATOR_LINE);
        builder.append(userComments).append("\n");
        builder.append(SEPARATOR_LINE).append("\n");
        message.setText(builder.toString());
        message.saveChanges();

        Transport.send(message);

        log.debug("Feedback mail sent successfully to {}", config.getString("mail.feedback"));
    } catch (MessagingException e) {
        log.error("Error sending feedback mail to {}", config.getString("mail.feedback"), e);
        throw new MailException("Error sending feedback mail to " + config.getString("mail.feedback"), e);
    }
}

From source file:ch.entwine.weblounge.kernel.mail.SmtpService.java

/**
 * Method to send a test message./*from  w  w  w.  ja  v a2s  .  com*/
 * 
 * @throws MessagingException
 *           if sending the message failed
 */
private void sendTestMessage(String recipient) throws MessagingException {
    MimeMessage message = createMessage();
    message.addRecipient(RecipientType.TO, new InternetAddress(recipient));
    message.setSubject("Test from Weblounge");
    message.setText("Hello world");
    message.saveChanges();
    send(message);
}

From source file:ftpclient.FTPManager.java

public boolean sendUserMail(String uploadedFileName) {
    if (settings != null) {
        try {//from ww  w  . j a  va 2 s.c  o  m
            String userEmail = db.getUserEmail(uid);
            Properties props = System.getProperties();
            props.setProperty("mail.smtp.host", settings.getSenderEmailHost());
            props.setProperty("mail.smtp.auth", "true");
            //            props.put("mail.smtp.starttls.enable", "true");
            //            props.put("mail.smtp.port", "587");
            Session s = Session.getDefaultInstance(props, new Authenticator() {

                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(settings.getSenderLogin(),
                            new String(settings.getSenderPassword()));
                }
            });
            MimeMessage msg = new MimeMessage(s);
            msg.setFrom(settings.getSenderEmail());
            msg.addRecipients(Message.RecipientType.TO, userEmail);
            msg.setSubject("FTP action");
            msg.setText("You have succesfully uploaded file " + uploadedFileName);
            Transport.send(msg);
            return true;
        } catch (MessagingException ex) {
            Logger.getLogger(FTPManager.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
    } else {
        return false;
    }
}

From source file:mx.unam.pixel.controller.MailController.java

public void enviaMensaje(String mensaje) {
    try {/*  w w w.  j  a v  a  2  s  .  c om*/
        Properties props = new Properties();

        // Nombre del host de correo, es smtp.gmail.com
        props.setProperty("mail.smtp.host", "smtp.gmail.com");

        // TLS si est disponible
        props.setProperty("mail.smtp.starttls.enable", "true");

        // Puerto de gmail para envio de correos
        props.setProperty("mail.smtp.port", "587");

        // Nombre del usuario
        props.setProperty("mail.smtp.user", "ejemplo@gmail.com");

        // Si requiere o no usuario y password para conectarse.
        props.setProperty("mail.smtp.auth", "true");

        // Preparamos la sesion
        Session session = Session.getDefaultInstance(props);
        //session.setDebug(true);

        //Construimos el mensage
        MimeMessage message = new MimeMessage(session);
        InternetAddress cuenta = new InternetAddress("enrique.wps@gmail.com");
        message.setFrom(); //Correo electronico que manda el mensaja
        message.addRecipient(Message.RecipientType.TO, new InternetAddress("vampa@ciencias.unam.mx"));
        message.setSubject("Test MUFFIN");
        message.setText("Test Muffin Cuerpo");
        // Abrimos la comunicacion 
        Transport t = session.getTransport("smtp");

        t.connect("dasds@gmail.com", "asdsadas"); // Ususario y contrasea
        t.sendMessage(message, message.getAllRecipients());
        // Cierre
        t.close();

    } catch (AddressException ex) {
        System.err.println("er");
    } catch (MessagingException ex) {
        Logger.getLogger(MailController.class.getName()).log(Level.SEVERE, null, ex);
    }

}

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

private void sendEmail(User user, String email, Timestamp resetDate) throws MessagingException {
    Properties props = new Properties();
    props.put("mail.smtp.host", "localhost");
    Session mailSession = Session.getDefaultInstance(props, null);

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

    String resetCode = UserService.getResetCode(configuration.getSecret(), user.getNick(), email, resetDate);

    msg.addRecipient(RecipientType.TO, new InternetAddress(email));
    msg.setSubject("Your password @linux.org.ru");
    msg.setSentDate(new Date());
    msg.setText("?!\n\n"
            + "? ??  ?   ?? http://www.linux.org.ru/reset-password\n\n"
            + "  " + user.getNick() + ",  ?: " + resetCode + "\n\n"
            + "!");

    Transport.send(msg);//  ww  w  .  jav a  2  s. com
}

From source file:com.nokia.helium.core.EmailDataSender.java

/**
 * Send xml data/*  www  .jav  a2 s . c  o m*/
 * 
 * @param String purpose of this email
 * @param String file to send
 * @param String mime type
 * @param String subject of email
 * @param String header of mail
 * @param boolean compress data if true
 */
public void sendData(String purpose, File fileToSend, String mimeType, String subject, String header,
        boolean compressData) throws EmailSendException {
    try {
        log.debug("sendData:Send file: " + fileToSend + " and mimetype: " + mimeType);
        if (fileToSend != null && fileToSend.exists()) {
            InternetAddress[] toAddresses = getToAddressList();
            Properties props = new Properties();
            if (smtpServerAddress != null) {
                log.debug("sendData:smtp address: " + smtpServerAddress);
                props.setProperty("mail.smtp.host", smtpServerAddress);
            }
            Session mailSession = Session.getDefaultInstance(props, null);
            MimeMessage message = new MimeMessage(mailSession);
            message.setSubject(subject == null ? "" : subject);
            MimeMultipart multipart = new MimeMultipart("related");
            BodyPart messageBodyPart = new MimeBodyPart();
            ByteArrayDataSource dataSrc = null;
            String fileName = fileToSend.getName();
            if (compressData) {
                log.debug("Sending compressed data");
                dataSrc = compressFile(fileToSend);
                dataSrc.setName(fileName + ".gz");
                messageBodyPart.setFileName(fileName + ".gz");
            } else {
                log.debug("Sending uncompressed data:");
                dataSrc = new ByteArrayDataSource(new FileInputStream(fileToSend), mimeType);

                message.setContent(FileUtils.readFileToString(fileToSend), "text/html");
                multipart = null;
            }
            String headerToSend = null;
            if (header == null) {
                headerToSend = "";
            }
            messageBodyPart.setHeader("helium-bld-data", headerToSend);
            messageBodyPart.setDataHandler(new DataHandler(dataSrc));

            if (multipart != null) {
                multipart.addBodyPart(messageBodyPart); // add to the
                // multipart
                message.setContent(multipart);
            }
            try {
                message.setFrom(getFromAddress());
            } catch (AddressException e) {
                throw new EmailSendException("Error retrieving the from address: " + e.getMessage(), e);
            } catch (LDAPException e) {
                throw new EmailSendException("Error retrieving the from address: " + e.getMessage(), e);
            }
            message.addRecipients(Message.RecipientType.TO, toAddresses);
            log.info("Sending email alert: " + subject);
            Transport.send(message);
        }
    } catch (MessagingException e) {
        String fullErrorMessage = "Failed sending e-mail: " + purpose;
        if (e.getMessage() != null) {
            fullErrorMessage += ": " + e.getMessage();
        }
        throw new EmailSendException(fullErrorMessage, e);
    } catch (IOException e) {
        String fullErrorMessage = "Failed sending e-mail: " + purpose;
        if (e.getMessage() != null) {
            fullErrorMessage += ": " + e.getMessage();
        }
        // We are Ignoring the errors as no need to fail the build.
        throw new EmailSendException(fullErrorMessage, e);
    }
}

From source file:com.bia.yahoomailjava.YahooMailService.java

/**
 *
 * @param addressTo//from  w  w w. j a v a 2 s . c om
 * @param subject
 * @param message
 *
 */
private void send(InternetAddress[] addressTo, String subject, String message) {
    try {
        MimeMessage msg = new MimeMessage(createSession());
        msg.setFrom(new InternetAddress(USERNAME));
        msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);
        msg.setSubject(subject);
        msg.setText(message);
        Transport.send(msg);
    } catch (Exception ex) {
        //logger.warn(ex.getMessage(), ex);
        throw new RuntimeException(ex);
    }
}