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:org.j2free.email.EmailService.java

private void send(InternetAddress from, InternetAddress[] recipients, String subject, String body,
        ContentType contentType, Priority priority, boolean ccSender)
        throws AddressException, MessagingException, RejectedExecutionException {
    MimeMessage message = new MimeMessage(session);
    message.setFrom(from);/*from   w w w  .  ja v a2 s  .c  o  m*/
    message.setRecipients(Message.RecipientType.TO, recipients);

    for (Map.Entry<String, String> header : headers.entrySet())
        message.setHeader(header.getKey(), header.getValue());

    // CC the sender if they want
    if (ccSender)
        message.addRecipient(Message.RecipientType.CC, from);

    message.setReplyTo(new InternetAddress[] { from });

    message.setSubject(subject);
    message.setSentDate(new Date());

    if (contentType == ContentType.PLAIN) {
        // Just set the body as plain text
        message.setText(body, "UTF-8");
    } else {
        MimeMultipart multipart = new MimeMultipart("alternative");

        // Create the text part
        MimeBodyPart text = new MimeBodyPart();
        text.setText(new HtmlFilter().filterForEmail(body), "UTF-8");

        // Add the text part
        multipart.addBodyPart(text);

        // Create the HTML portion
        MimeBodyPart html = new MimeBodyPart();
        html.setContent(body, ContentType.HTML.toString());

        // Add the HTML portion
        multipart.addBodyPart(html);

        // set the message content
        message.setContent(multipart);
    }
    enqueue(message, priority);
}

From source file:org.opens.kbaccess.controller.utils.AMailerController.java

/**
 * Send a mail to the specified recipients.
 * //from w  w  w .jav a  2 s .co  m
 * @param subject The mail's subject
 * @param message The mail's body
 * @param recipients The adressee
 * @return true if the send succeed,
 *         false otherwise
 */
public boolean sendMail(String subject, String message, String[] recipients) {
    Session session;
    MimeMessage mimeMessage;
    Properties properties;

    // sanity check
    if (recipients.length == 0) {
        return true;
    }
    // set-up session
    properties = new Properties();
    properties.put("mail.smtp.host", mailingServiceProperties.getSmtpHost());
    session = Session.getDefaultInstance(properties);
    //session.setDebug(true);
    try {
        Address from;
        Address[] to = new InternetAddress[recipients.length];

        // set sender
        from = new InternetAddress(mailingServiceProperties.getDefaultReturnAddress());
        // initialize recipients list
        for (int i = 0; i < to.length; ++i) {
            to[i] = new InternetAddress(recipients[i]);
        }
        // create message
        mimeMessage = new MimeMessage(session);
        mimeMessage.setSender(from);
        mimeMessage.setFrom(from);
        mimeMessage.setReplyTo(new Address[] { from });
        mimeMessage.setRecipients(Message.RecipientType.TO, to);
        mimeMessage.setSubject(subject);
        mimeMessage.setText(message, "utf-8");
        // send it
        Transport.send(mimeMessage);
    } catch (MessagingException ex) {
        LogFactory.getLog(GuestController.class).error("Unable to send email", ex);
        return false;
    }
    return true;
}

From source file:com.gamesalutes.utils.email.DefaultEmailServiceImpl.java

public void send(EmailModel model) throws EmailException {

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Sending email: " + model);

    if (model == null)
        throw new NullPointerException("model");

    Properties emailProps;/*from  w  w  w  .  j a  v  a  2s. c o  m*/
    Session emailSession;

    // set the relay host as a property of the email session
    emailProps = new Properties();
    emailProps.setProperty("mail.transport.protocol", "smtp");
    emailProps.put("mail.smtp.host", host);
    emailProps.setProperty("mail.smtp.port", String.valueOf(port));
    // set the timeouts
    emailProps.setProperty("mail.smtp.connectiontimeout", String.valueOf(SOCKET_CONNECT_TIMEOUT_MS));
    emailProps.setProperty("mail.smtp.timeout", String.valueOf(SOCKET_IO_TIMEOUT_MS));

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Email properties: " + emailProps);

    // set up email session
    emailSession = Session.getInstance(emailProps, null);
    emailSession.setDebug(false);

    String from;
    String displayFrom;

    String body;
    String subject;
    List<EmailAttachment> attachments;

    if (model.getFrom() == null)
        throw new NullPointerException("from");
    if (MiscUtils.isEmpty(model.getTo()) && MiscUtils.isEmpty(model.getBcc())
            && MiscUtils.isEmpty(model.getCc()))
        throw new IllegalArgumentException("model has no addresses");

    from = model.getFrom();
    displayFrom = model.getDisplayFrom();
    body = model.getBody();
    subject = model.getSubject();
    attachments = model.getAttachments();

    MimeMessage emailMessage;
    InternetAddress emailAddressFrom;

    // create an email message from the current session
    emailMessage = new MimeMessage(emailSession);

    // set the from
    try {
        emailAddressFrom = new InternetAddress(from, displayFrom);
        emailMessage.setFrom(emailAddressFrom);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    if (!MiscUtils.isEmpty(model.getTo()))
        setEmailRecipients(emailMessage, model.getTo(), RecipientType.TO);
    if (!MiscUtils.isEmpty(model.getCc()))
        setEmailRecipients(emailMessage, model.getCc(), RecipientType.CC);
    if (!MiscUtils.isEmpty(model.getBcc()))
        setEmailRecipients(emailMessage, model.getBcc(), RecipientType.BCC);

    try {

        if (!MiscUtils.isEmpty(subject))
            emailMessage.setSubject(subject);

        Multipart multipart = new MimeMultipart();

        if (body != null) {
            // create the message part
            MimeBodyPart messageBodyPart = new MimeBodyPart();

            //fill message
            String bodyContentType;
            //        body = Utils.base64Encode(body);
            bodyContentType = "text/html; charset=UTF-8";

            messageBodyPart.setContent(body, bodyContentType);
            //Content-Transfer-Encoding : base64
            //        messageBodyPart.addHeader("Content-Transfer-Encoding", "base64");
            multipart.addBodyPart(messageBodyPart);
        }
        // Part two is attachment
        if (attachments != null && !attachments.isEmpty()) {
            try {
                for (EmailAttachment a : attachments) {
                    MimeBodyPart attachBodyPart = new MimeBodyPart();
                    // don't base 64 encode
                    DataSource source = new StreamDataSource(
                            new DefaultStreamFactory(a.getInputStream(), false), a.getName(),
                            a.getContentType());
                    attachBodyPart.setDataHandler(new DataHandler(source));
                    attachBodyPart.setFileName(a.getName());
                    attachBodyPart.setHeader("Content-Type", a.getContentType());
                    attachBodyPart.addHeader("Content-Transfer-Encoding", "base64");

                    // add the attachment to the message
                    multipart.addBodyPart(attachBodyPart);

                }
            }
            // close all the input streams
            finally {
                for (EmailAttachment a : attachments)
                    MiscUtils.closeStream(a.getInputStream());
            }
        }

        // set the content
        emailMessage.setContent(multipart);
        emailMessage.saveChanges();

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Sending email message: " + emailMessage);

        Transport.send(emailMessage);

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Sending email complete.");

    } catch (Exception e) {
        throw new EmailException(e);
    }

}

From source file:org.apache.james.transport.mailets.StripAttachmentTest.java

@Test
public void testSimpleAttachment() throws MessagingException, IOException {
    Mailet mailet = initMailet();/*ww w.j  av  a2s . com*/

    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));

    MimeMultipart mm = new MimeMultipart();
    MimeBodyPart mp = new MimeBodyPart();
    mp.setText("simple text");
    mm.addBodyPart(mp);
    String body = "\u0023\u00A4\u00E3\u00E0\u00E9";
    MimeBodyPart mp2 = new MimeBodyPart(new ByteArrayInputStream(
            ("Content-Transfer-Encoding: 8bit\r\nContent-Type: application/octet-stream; charset=utf-8\r\n\r\n"
                    + body).getBytes("UTF-8")));
    mp2.setDisposition("attachment");
    mp2.setFileName("10.tmp");
    mm.addBodyPart(mp2);
    String body2 = "\u0014\u00A3\u00E1\u00E2\u00E4";
    MimeBodyPart mp3 = new MimeBodyPart(new ByteArrayInputStream(
            ("Content-Transfer-Encoding: 8bit\r\nContent-Type: application/octet-stream; charset=utf-8\r\n\r\n"
                    + body2).getBytes("UTF-8")));
    mp3.setDisposition("attachment");
    mp3.setFileName("temp.zip");
    mm.addBodyPart(mp3);
    message.setSubject("test");
    message.setContent(mm);
    message.saveChanges();

    Mail mail = FakeMail.builder().mimeMessage(message).build();

    mailet.service(mail);

    ByteArrayOutputStream rawMessage = new ByteArrayOutputStream();
    mail.getMessage().writeTo(rawMessage, new String[] { "Bcc", "Content-Length", "Message-ID" });

    @SuppressWarnings("unchecked")
    Collection<String> c = (Collection<String>) mail
            .getAttribute(StripAttachment.SAVED_ATTACHMENTS_ATTRIBUTE_KEY);
    Assert.assertNotNull(c);

    Assert.assertEquals(1, c.size());

    String name = c.iterator().next();

    File f = new File("./" + name);
    try {
        InputStream is = new FileInputStream(f);
        String savedFile = toString(is);
        is.close();
        Assert.assertEquals(body, savedFile);
    } finally {
        FileUtils.deleteQuietly(f);
    }
}

From source file:bean.RedSocial.java

/**
 * //from   w  w  w  . j  av a 2 s.c  om
 * @param _username
 * @param _email
 * @param _password 
 */
@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false, rollbackFor = transactionalBusinessException.ComentariosViaException.class)
public void solicitarAcceso(String _username, String _email, String _password) {
    if (daoUsuario.obtenerUsuario(_username) != null) {
        throw new exceptionsBusiness.UsernameNoDisponible();
    }

    String hash = BCrypt.hashpw(_password, BCrypt.gensalt());

    Token token = new Token(_username, _email, hash);
    daoToken.guardarToken(token);

    //enviar token de acceso a la direccion email

    String correoEnvia = "skala2climbing@gmail.com";
    String claveCorreo = "vNspLa5H";

    // La configuracin para enviar correo
    Properties properties = new Properties();
    properties.put("mail.smtp.host", "smtp.gmail.com");
    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.smtp.port", "587");
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.user", correoEnvia);
    properties.put("mail.password", claveCorreo);

    // Obtener la sesion
    Session session = Session.getInstance(properties, null);

    try {
        // Crear el cuerpo del mensaje
        MimeMessage mimeMessage = new MimeMessage(session);

        // Agregar quien enva el correo
        mimeMessage.setFrom(new InternetAddress(correoEnvia, "Skala2Climbing"));

        // Los destinatarios
        InternetAddress[] internetAddresses = { new InternetAddress(token.getEmail()) };

        // Agregar los destinatarios al mensaje
        mimeMessage.setRecipients(Message.RecipientType.TO, internetAddresses);

        // Agregar el asunto al correo
        mimeMessage.setSubject("Confirmacin de registro");

        // Creo la parte del mensaje
        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        String ip = "90.165.24.228";
        mimeBodyPart.setText("Confirme su registro pulsando en el siguiente enlace: http://" + ip
                + ":8383/redsocialcolaborativaclientangularjs/confirmacion.html?" + "token="
                + token.getToken());
        //mimeBodyPart.setText("Confirme su registro pulsando en el siguiente enlace: "+"Enlace an no disponible");

        // Crear el multipart para agregar la parte del mensaje anterior
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(mimeBodyPart);

        // Agregar el multipart al cuerpo del mensaje
        mimeMessage.setContent(multipart);

        // Enviar el mensaje
        Transport transport = session.getTransport("smtp");
        transport.connect(correoEnvia, claveCorreo);
        transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
        transport.close();

    } catch (UnsupportedEncodingException | MessagingException ex) {
        throw new ErrorEnvioEmail();
    }

}

From source file:com.midori.confluence.plugin.mail2news.Mail2NewsJob.java

/**
 * Send an mail containing the error message back to the
 * user which sent the given message.//from  w  w w .  jav  a  2  s.co m
 *
 * @param m The message which produced an error while handling it.
 * @param error The error string.
 */
private void sendErrorMessage(Message m, String error) throws Exception {
    /* get the SMTP mail server */
    SMTPMailServer smtpMailServer = MailFactory.getServerManager().getDefaultSMTPMailServer();
    if (smtpMailServer == null) {
        log.warn("Failed to send error message as no SMTP server is configured");
        return;
    }

    /* get system properties */
    Properties props = System.getProperties();

    /* Setup mail server */
    props.put("mail.smtp.host", smtpMailServer.getHostname());

    /* get a session */
    Session session = Session.getDefaultInstance(props, null);
    /* create the message */
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(smtpMailServer.getDefaultFrom()));
    String senderEmail = getEmailAddressFromMessage(m);
    if (senderEmail == "") {
        throw new Exception("Unknown sender of email.");
    }
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(senderEmail));
    message.setSubject("[mail2news] Error while handling message (" + m.getSubject() + ")");
    message.setText("An error occurred while handling your message:\n\n  " + error
            + "\n\nPlease contact the administrator to solve the problem.\n");

    /* send the message */
    Transport tr = session.getTransport("smtp");
    if (StringUtils.isBlank(smtpMailServer.getSmtpPort())) {
        tr.connect(smtpMailServer.getHostname(), smtpMailServer.getUsername(), smtpMailServer.getPassword());
    } else {
        int smtpPort = Integer.parseInt(smtpMailServer.getSmtpPort());
        tr.connect(smtpMailServer.getHostname(), smtpPort, smtpMailServer.getUsername(),
                smtpMailServer.getPassword());
    }
    message.saveChanges();
    tr.sendMessage(message, message.getAllRecipients());
    tr.close();
}

From source file:com.commoncoupon.mail.EmailProcessor.java

public Integer call() throws Exception {
    MimeMessage message = new MimeMessage(getSession());

    try {/*from www .j  ava2 s . c  om*/
        if (from != null && (from != null && from.trim() != "")) {
            InternetAddress sentFrom = new InternetAddress(from);
            message.setFrom(sentFrom);
            if (log.isDebugEnabled())
                log.debug("Email sent from: " + sentFrom);
        }

        if (to != null && to.length > 0) {
            InternetAddress[] sendTo = new InternetAddress[to.length];
            for (int i = 0; i < to.length; i++) {
                sendTo[i] = new InternetAddress((String) to[i]);
                if (log.isDebugEnabled())
                    log.debug("Sending e-mail to: " + to[i]);
            }
            message.setRecipients(Message.RecipientType.TO, sendTo);
        }

        if (cc != null && cc.length > 0) {
            InternetAddress[] copyTo = new InternetAddress[cc.length];
            for (int i = 0; i < cc.length; i++) {
                copyTo[i] = new InternetAddress((String) cc[i]);
                if (log.isDebugEnabled())
                    log.debug("Copying e-mail to: " + cc[i]);
            }
            message.setRecipients(Message.RecipientType.CC, copyTo);
        }
        message.setSentDate(new Date());
        message.setSubject(subject);
        message.setContent(content, mimeType);
        Transport.send(message);
    } catch (Exception e) {
        log.error("Failed to send email.", e);
        return (1);
    }

    return (0);
}

From source file:com.sonicle.webtop.core.app.WebTopApp.java

public void sendEmail(javax.mail.Session session, InternetAddress from, Collection<InternetAddress> to,
        Collection<InternetAddress> cc, Collection<InternetAddress> bcc, String subject, MimeMultipart part)
        throws MessagingException {

    try {//from   w  w  w.j a v a  2  s .c  o  m
        subject = MimeUtility.encodeText(subject);
    } catch (Exception ex) {
    }

    MimeMessage message = new MimeMessage(session);
    message.setSubject(subject);
    message.addFrom(new InternetAddress[] { from });

    if (to != null) {
        for (InternetAddress ia : to)
            message.addRecipient(Message.RecipientType.TO, ia);
    }
    if (cc != null) {
        for (InternetAddress ia : cc)
            message.addRecipient(Message.RecipientType.CC, ia);
    }
    if (bcc != null) {
        for (InternetAddress ia : bcc)
            message.addRecipient(Message.RecipientType.BCC, ia);
    }

    message.setContent(part);
    message.setSentDate(new java.util.Date());
    Transport.send(message);
}

From source file:com.sangupta.jerry.email.service.impl.SmtpEmailServiceImpl.java

/**
 * @see com.sangupta.jerry.email.service.EmailService#sendEmail(com.sangupta.jerry.email.domain.Email)
 *//* w  w w  .  j av a  2 s .  c om*/
@Override
public boolean sendEmail(final Email email) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {

        public void prepare(MimeMessage mimeMessage) throws Exception {
            if (AssertUtils.isNotEmpty(email.getTo())) {
                for (EmailAddress address : email.getTo()) {
                    mimeMessage.setRecipient(RecipientType.TO, address.getInternetAddress());
                }
            }

            if (AssertUtils.isNotEmpty(email.getCc())) {
                for (EmailAddress address : email.getCc()) {
                    mimeMessage.setRecipient(RecipientType.CC, address.getInternetAddress());
                }
            }

            if (AssertUtils.isNotEmpty(email.getBcc())) {
                for (EmailAddress address : email.getBcc()) {
                    mimeMessage.setRecipient(RecipientType.BCC, address.getInternetAddress());
                }
            }

            if (AssertUtils.isNotEmpty(email.getReplyTo())) {
                Address[] replyTo = new Address[email.getReplyTo().size()];
                int counter = 0;
                for (EmailAddress address : email.getReplyTo()) {
                    replyTo[counter++] = address.getInternetAddress();
                }
                mimeMessage.setReplyTo(replyTo);
            }

            mimeMessage.setFrom(email.getFrom().getInternetAddress());
            mimeMessage.setSubject(email.getSubject());
            mimeMessage.setContent(email.getText(), "text/html; charset=utf-8");
        }

    };

    try {
        this.mailSender.send(preparator);
        return true;
    } catch (MailException e) {
        LOGGER.error("Unable to send email", e);
    }

    return false;
}

From source file:org.apache.james.transport.mailets.StripAttachmentTest.java

@Test
public void testToAndFromAttributes() throws MessagingException, IOException {
    Mailet strip = new StripAttachment();
    FakeMailetConfig mci = new FakeMailetConfig("Test", FakeMailContext.defaultContext());
    mci.setProperty("attribute", "my.attribute");
    mci.setProperty("remove", "all");
    mci.setProperty("notpattern", ".*\\.tmp.*");
    strip.init(mci);/*  w w  w . j  a v  a  2  s .c o m*/

    Mailet recover = new RecoverAttachment();
    FakeMailetConfig mci2 = new FakeMailetConfig("Test", FakeMailContext.defaultContext());
    mci2.setProperty("attribute", "my.attribute");
    recover.init(mci2);

    Mailet onlyText = new OnlyText();
    onlyText.init(new FakeMailetConfig("Test", FakeMailContext.defaultContext()));

    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));

    MimeMultipart mm = new MimeMultipart();
    MimeBodyPart mp = new MimeBodyPart();
    mp.setText("simple text");
    mm.addBodyPart(mp);
    String body = "\u0023\u00A4\u00E3\u00E0\u00E9";
    MimeBodyPart mp2 = new MimeBodyPart(new ByteArrayInputStream(
            ("Content-Transfer-Encoding: 8bit\r\nContent-Type: application/octet-stream; charset=utf-8\r\n\r\n"
                    + body).getBytes("UTF-8")));
    mp2.setDisposition("attachment");
    mp2.setFileName("=?iso-8859-15?Q?=E9_++++Pubblicit=E0_=E9_vietata____Milano9052.tmp?=");
    mm.addBodyPart(mp2);
    String body2 = "\u0014\u00A3\u00E1\u00E2\u00E4";
    MimeBodyPart mp3 = new MimeBodyPart(new ByteArrayInputStream(
            ("Content-Transfer-Encoding: 8bit\r\nContent-Type: application/octet-stream; charset=utf-8\r\n\r\n"
                    + body2).getBytes("UTF-8")));
    mp3.setDisposition("attachment");
    mp3.setFileName("temp.zip");
    mm.addBodyPart(mp3);
    message.setSubject("test");
    message.setContent(mm);
    message.saveChanges();
    Mail mail = FakeMail.builder().mimeMessage(message).build();

    Assert.assertTrue(mail.getMessage().getContent() instanceof MimeMultipart);
    Assert.assertEquals(3, ((MimeMultipart) mail.getMessage().getContent()).getCount());

    strip.service(mail);

    Assert.assertTrue(mail.getMessage().getContent() instanceof MimeMultipart);
    Assert.assertEquals(1, ((MimeMultipart) mail.getMessage().getContent()).getCount());

    onlyText.service(mail);

    Assert.assertFalse(mail.getMessage().getContent() instanceof MimeMultipart);

    Assert.assertEquals("simple text", mail.getMessage().getContent());

    // prova per caricare il mime message da input stream che altrimenti
    // javamail si comporta differentemente.
    String mimeSource = "Message-ID: <26194423.21197328775426.JavaMail.bago@bagovista>\r\nSubject: test\r\nMIME-Version: 1.0\r\nContent-Type: text/plain; charset=us-ascii\r\nContent-Transfer-Encoding: 7bit\r\n\r\nsimple text";

    MimeMessage mmNew = new MimeMessage(Session.getDefaultInstance(new Properties()),
            new ByteArrayInputStream(mimeSource.getBytes("UTF-8")));

    mmNew.writeTo(System.out);
    mail.setMessage(mmNew);

    recover.service(mail);

    Assert.assertTrue(mail.getMessage().getContent() instanceof MimeMultipart);
    Assert.assertEquals(2, ((MimeMultipart) mail.getMessage().getContent()).getCount());

    Object actual = ((MimeMultipart) mail.getMessage().getContent()).getBodyPart(1).getContent();
    if (actual instanceof ByteArrayInputStream) {
        Assert.assertEquals(body2, toString((ByteArrayInputStream) actual));
    } else {
        Assert.assertEquals(body2, actual);
    }

}