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.codice.ddf.catalog.ui.query.monitor.email.EmailNotifier.java

private void sendEmailForWorkspace(WorkspaceMetacardImpl workspaceMetacard, Long hitCount, String email) {

    String emailBody = metacardFormatter.format(bodyTemplate, workspaceMetacard, hitCount);

    String subject = metacardFormatter.format(subjectTemplate, workspaceMetacard, hitCount);

    Session session = smtpClient.createSession();

    try {//from  w ww.jav a  2s  .  c  o  m
        MimeMessage mimeMessage = new MimeMessage(session);

        mimeMessage.setFrom(new InternetAddress(fromEmail));

        mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(email));

        mimeMessage.setSubject(subject);

        mimeMessage.setText(emailBody);

        LOGGER.trace("Attempting to send email");

        smtpClient.send(mimeMessage);

    } catch (MessagingException e) {
        LOGGER.warn("unable to send email to {}", email, e);
    }
}

From source file:org.xwiki.mail.integration.JavaIntegrationTest.java

@Test
public void sendHTMLAndCalendarInvitationMail() throws Exception {
    // Step 1: Create a JavaMail Session
    Session session = Session.getInstance(this.configuration.getAllProperties());

    // Step 2: Create the Message to send
    MimeMessage message = new MimeMessage(session);
    message.setSubject("subject");
    message.setRecipient(RecipientType.TO, new InternetAddress("john@doe.com"));

    // Step 3: Add the Message Body
    Multipart multipart = new MimeMultipart("alternative");
    // Add an HTML body part
    multipart.addBodyPart(//from  ww w.  j  a  v  a  2  s  .co  m
            this.htmlBodyPartFactory.create("<font size=\"\\\"2\\\"\">simple meeting invitation</font>",
                    Collections.<String, Object>emptyMap()));
    // Add the Calendar invitation body part
    String calendarContent = "BEGIN:VCALENDAR\r\n" + "METHOD:REQUEST\r\n" + "PRODID: Meeting\r\n"
            + "VERSION:2.0\r\n" + "BEGIN:VEVENT\r\n" + "DTSTAMP:20140616T164100\r\n"
            + "DTSTART:20140616T164100\r\n" + "DTEND:20140616T194100\r\n" + "SUMMARY:test request\r\n"
            + "UID:324\r\n"
            + "ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE:MAILTO:john@doe.com\r\n"
            + "ORGANIZER:MAILTO:john@doe.com\r\n" + "LOCATION:on the net\r\n"
            + "DESCRIPTION:learn some stuff\r\n" + "SEQUENCE:0\r\n" + "PRIORITY:5\r\n" + "CLASS:PUBLIC\r\n"
            + "STATUS:CONFIRMED\r\n" + "TRANSP:OPAQUE\r\n" + "BEGIN:VALARM\r\n" + "ACTION:DISPLAY\r\n"
            + "DESCRIPTION:REMINDER\r\n" + "TRIGGER;RELATED=START:-PT00H15M00S\r\n" + "END:VALARM\r\n"
            + "END:VEVENT\r\n" + "END:VCALENDAR";
    Map<String, Object> parameters = new HashMap<>();
    parameters.put("mimetype", "text/calendar;method=CANCEL");
    parameters.put("headers", Collections.singletonMap("Content-Class", "urn:content-classes:calendarmessage"));
    multipart.addBodyPart(this.defaultBodyPartFactory.create(calendarContent, parameters));

    message.setContent(multipart);

    // Step 4: Send the mail and wait for it to be sent
    this.sender.sendAsynchronously(Arrays.asList(message), session, null);

    // Verify that the mail has been received (wait maximum 30 seconds).
    this.mail.waitForIncomingEmail(30000L, 1);
    MimeMessage[] messages = this.mail.getReceivedMessages();

    assertEquals("subject", messages[0].getHeader("Subject", null));
    assertEquals("john@doe.com", messages[0].getHeader("To", null));

    assertEquals(2, ((MimeMultipart) messages[0].getContent()).getCount());

    BodyPart htmlBodyPart = ((MimeMultipart) messages[0].getContent()).getBodyPart(0);
    assertEquals("text/html; charset=UTF-8", htmlBodyPart.getHeader("Content-Type")[0]);
    assertEquals("<font size=\"\\\"2\\\"\">simple meeting invitation</font>", htmlBodyPart.getContent());

    BodyPart calendarBodyPart = ((MimeMultipart) messages[0].getContent()).getBodyPart(1);
    assertEquals("text/calendar;method=CANCEL", calendarBodyPart.getHeader("Content-Type")[0]);
    InputStream is = (InputStream) calendarBodyPart.getContent();
    assertEquals(calendarContent, IOUtils.toString(is));
}

From source file:org.opencastproject.kernel.mail.SmtpService.java

/**
 * Method to send a test message.//from  w w w  . ja  va 2  s.c o  m
 * 
 * @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 Matterhorn");
    message.setText("Hello world");
    message.saveChanges();
    send(message);
}

From source file:org.openmeetings.test.calendar.TestSendIcalMessage.java

private void sendIcalMessage() throws Exception {

    log.debug("sendIcalMessage");

    // Evaluating Configuration Data
    String smtpServer = cfgManagement.getConfKey(3, "smtp_server").getConf_value();
    String smtpPort = cfgManagement.getConfKey(3, "smtp_port").getConf_value();
    // String from = "openmeetings@xmlcrm.org";
    String from = cfgManagement.getConfKey(3, "system_email_addr").getConf_value();

    String emailUsername = cfgManagement.getConfKey(3, "email_username").getConf_value();
    String emailUserpass = cfgManagement.getConfKey(3, "email_userpass").getConf_value();

    Properties props = System.getProperties();

    props.put("mail.smtp.host", smtpServer);
    props.put("mail.smtp.port", smtpPort);

    Configuration conf = cfgManagement.getConfKey(3, "mail.smtp.starttls.enable");
    if (conf != null) {
        if (conf.getConf_value().equals("1")) {
            props.put("mail.smtp.starttls.enable", "true");
        }/*  ww  w  .  j av a  2  s.c  o m*/
    }

    // Check for Authentification
    Session session = null;
    if (emailUsername != null && emailUsername.length() > 0 && emailUserpass != null
            && emailUserpass.length() > 0) {
        // use SMTP Authentication
        props.put("mail.smtp.auth", "true");
        session = Session.getDefaultInstance(props, new SmtpAuthenticator(emailUsername, emailUserpass));
    } else {
        // not use SMTP Authentication
        session = Session.getDefaultInstance(props, null);
    }

    // Building MimeMessage
    MimeMessage mimeMessage = new MimeMessage(session);
    mimeMessage.setSubject(subject);
    mimeMessage.setFrom(new InternetAddress(from));
    mimeMessage.addRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients, false));

    // -- Create a new message --
    BodyPart msg = new MimeBodyPart();
    msg.setDataHandler(new DataHandler(new ByteArrayDataSource(htmlBody, "text/html; charset=\"utf-8\"")));

    Multipart multipart = new MimeMultipart();

    BodyPart iCalAttachment = new MimeBodyPart();
    iCalAttachment.setDataHandler(new DataHandler(new javax.mail.util.ByteArrayDataSource(
            new ByteArrayInputStream(iCalMimeBody), "text/calendar;method=REQUEST;charset=\"UTF-8\"")));
    iCalAttachment.setFileName("invite.ics");

    multipart.addBodyPart(iCalAttachment);
    multipart.addBodyPart(msg);

    mimeMessage.setSentDate(new Date());
    mimeMessage.setContent(multipart);

    // -- Set some other header information --
    // mimeMessage.setHeader("X-Mailer", "XML-Mail");
    // mimeMessage.setSentDate(new Date());

    // Transport trans = session.getTransport("smtp");
    Transport.send(mimeMessage);

}

From source file:jenkins.plugins.mailer.tasks.MimeMessageBuilder.java

private void addSubject(MimeMessage msg) throws MessagingException {
    if (subject != null) {
        msg.setSubject(subject);
    }//from  w w  w  .  j a v a  2  s .  c  o  m
}

From source file:com.threepillar.labs.meeting.email.EmailInviteImpl.java

@Override
public void sendInvite(final String subject, final String description, final Participant from,
        final List<Participant> attendees, final Date startDate, final Date endDate, final String location)
        throws Exception {

    this.properties.put("mail.smtp.socketFactory.port", properties.get("mail.smtp.port"));
    this.properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    this.properties.put("mail.smtp.socketFactory.fallback", "false");

    validate();//w  ww.  jav a 2  s  .  co m

    LOG.info("Sending meeting invite");
    LOG.debug("Mail Properties :: " + this.properties);

    Session session;
    if (password != null) {
        session = Session.getInstance(this.properties, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
    } else {
        session = Session.getInstance(this.properties);
    }

    ICal cal = new ICal(subject, description, from, attendees, startDate, endDate, location);
    cal.init();

    StringBuffer sb = new StringBuffer();
    sb.append(from.getEmail());
    for (Participant bean : attendees) {
        if (sb.length() > 0) {
            sb.append(",");
        }
        sb.append(bean.getEmail());
    }
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from.getEmail()));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(sb.toString()));
    message.setSubject(subject);
    Multipart multipart = new MimeMultipart();
    MimeBodyPart iCal = new MimeBodyPart();
    iCal.setDataHandler(new DataHandler(new ByteArrayDataSource(new ByteArrayInputStream(cal.toByteArray()),
            "text/calendar;method=REQUEST;charset=\"UTF-8\"")));

    LOG.debug("Calender Request :: \n" + cal.toString());

    multipart.addBodyPart(iCal);
    message.setContent(multipart);
    Transport.send(message);
}

From source file:com.norconex.jef4.mail.SimpleMailer.java

/**
 * Sends an email./*www .j a va2s.c o  m*/
 * @param recipients email recipients ("To" field)
 * @param subject email subject
 * @param body email body (content)
 * @throws MessagingException problem sending email
 */
public final void send(final String[] recipients, final String subject, final String body)
        throws MessagingException {
    if (recipients == null || recipients.length == 0) {
        throw new IllegalArgumentException("No mail recipient provided.");
    }
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(sender));
    for (int i = 0; i < recipients.length; i++) {
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipients[i]));
    }
    message.setSubject(subject);
    message.setContent(body, contentType);
    Transport.send(message);
}

From source file:gov.nih.nci.cabig.caaers.esb.client.MessageNotificationService.java

public void sendMail(String[] to, String subject, String content, String attachment) throws Exception {

    MimeMessage message = caaersJavaMailSender.createMimeMessage();
    message.setSubject(subject);
    message.setFrom(new InternetAddress(configuration.get(Configuration.SYSTEM_FROM_EMAIL)));

    // use the true flag to indicate you need a multipart message
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setTo(to);//from  w w w. j a  va2 s  . c  o  m
    helper.setText(content);

    if (attachment != null) {
        File f = new File(attachment);
        FileSystemResource file = new FileSystemResource(f);
        helper.addAttachment(file.getFilename(), file);
    }

    caaersJavaMailSender.send(message);

}

From source file:egovframework.oe1.cms.cmm.notify.email.service.impl.EgovOe1SSLMailServiceImpl.java

protected void send(String subject, String content, String contentType) throws Exception {
    Properties props = new Properties();

    props.put("mail.transport.protocol", "smtps");
    props.put("mail.smtps.host", getHost());
    props.put("mail.smtps.auth", "true");

    Session mailSession = Session.getDefaultInstance(props);
    mailSession.setDebug(false);// w  w  w  .j a v a  2  s.  co m
    Transport transport = mailSession.getTransport();

    MimeMessage message = new MimeMessage(mailSession);
    message.setFrom(new InternetAddress("www.egovframe.org", "webmaster", "euc-kr"));
    message.setSubject(subject);

    MimeBodyPart mbp1 = new MimeBodyPart();
    mbp1.setText(content, "utf-8");

    Multipart mp = new MimeMultipart();
    mp.addBodyPart(mbp1);

    List<String> fileNames = getAtchFileIds();

    for (Iterator<String> it = fileNames.iterator(); it.hasNext();) {
        MimeBodyPart mbp2 = new MimeBodyPart();

        // attach the file to the message
        FileDataSource fds = new FileDataSource(it.next());
        mbp2.setDataHandler(new DataHandler(fds));

        mbp2.setFileName(MimeUtility.encodeText(fds.getName(), "euc-kr", "B")); // Q : ascii, B : 

        mp.addBodyPart(mbp2);
    }

    // add the Multipart to the message
    message.setContent(mp);

    for (Iterator<String> it = getReceivers().iterator(); it.hasNext();)
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(it.next()));

    transport.connect(getHost(), getPort(), getUsername(), getPassword());
    transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
    transport.close();
}

From source file:davmail.smtp.TestSmtp.java

public void testComplexToMessage() throws IOException, MessagingException, InterruptedException {
    String body = "Test message";
    MimeMessage mimeMessage = new MimeMessage((Session) null);
    mimeMessage.addHeader("To", "nickname <" + Settings.getProperty("davmail.to") + '>');
    mimeMessage.setSubject("Test subject");
    mimeMessage.setText(body);//from   w  ww .j  ava  2 s  . c  om
    sendAndCheckMessage(mimeMessage);
}