Java Code Examples for javax.mail.internet.MimeMessage#setHeader()

The following examples show how to use javax.mail.internet.MimeMessage#setHeader() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MailSenderSMTP.java    From rapidminer-studio with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void sendEmail(String address, String subject, String content, Map<String, String> headers,
					  UnaryOperator<String> properties) throws Exception {
	Session session = MailUtilities.makeSession(properties);
	if (session == null) {
		LogService.getRoot().log(Level.WARNING, SESSION_CREATION_FAILURE, address);
	}
	MimeMessage msg = new MimeMessage(session);
	msg.setRecipients(Message.RecipientType.TO, address);
	msg.setFrom();
	msg.setSubject(subject, "UTF-8");
	msg.setSentDate(new Date());
	msg.setText(content, "UTF-8");

	if (headers != null) {
		for (Entry<String, String> header : headers.entrySet()) {
			msg.setHeader(header.getKey(), header.getValue());
		}
	}
	Transport.send(msg);
}
 
Example 2
Source File: TestExtractEmailHeaders.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * NIFI-4326 adds a new feature to disable strict address parsing for
 * mailbox list header fields. This is a test case that asserts that
 * strict address parsing fails (when set to "strict=true") for malformed
 * addresses.
 */
@Test
public void testStrictParsingFailsForInvalidAddresses() throws Exception {
    final TestRunner runner = TestRunners.newTestRunner(new ExtractEmailHeaders());
    runner.setProperty(ExtractEmailHeaders.STRICT_PARSING, "true");

    MimeMessage simpleEmailMimeMessage = attachmentGenerator.SimpleEmailMimeMessage();

    simpleEmailMimeMessage.setHeader("From", "<bad_email>");
    simpleEmailMimeMessage.setHeader("To", "<>, Joe, <invalid>");

    ByteArrayOutputStream messageBytes = new ByteArrayOutputStream();
    try {
        simpleEmailMimeMessage.writeTo(messageBytes);
    } catch (IOException | MessagingException e) {
        e.printStackTrace();
    }

    runner.enqueue(messageBytes.toByteArray());
    runner.run();

    runner.assertTransferCount(ExtractEmailHeaders.REL_SUCCESS, 0);
    runner.assertTransferCount(ExtractEmailHeaders.REL_FAILURE, 1);
}
 
Example 3
Source File: EmailSendTool.java    From Lottery with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 此段代码用来发送普通电子邮件
 * 
 * @throws MessagingException
 * @throws UnsupportedEncodingException
 * @throws UnsupportedEncodingException
 */
public void send() throws MessagingException, UnsupportedEncodingException {
	Properties props = new Properties();
	Authenticator auth = new Email_Autherticator(); // 进行邮件服务器用户认证
	props.put("mail.smtp.host", host);
	props.put("mail.smtp.auth", "true");
	Session session = Session.getDefaultInstance(props, auth);
	// 设置session,和邮件服务器进行通讯。
	MimeMessage message = new MimeMessage(session);
	// message.setContent("foobar, "application/x-foobar"); // 设置邮件格式
	message.setSubject(mail_subject); // 设置邮件主题
	message.setText(mail_body); // 设置邮件正文
	message.setHeader(mail_head_name, mail_head_value); // 设置邮件标题

	message.setSentDate(new Date()); // 设置邮件发送日期
	Address address = new InternetAddress(mail_from, personalName);
	message.setFrom(address); // 设置邮件发送者的地址
	Address toAddress = new InternetAddress(mail_to); // 设置邮件接收方的地址
	message.addRecipient(Message.RecipientType.TO, toAddress);
	Transport.send(message); // 发送邮件
}
 
Example 4
Source File: SetMimeHeaderHandler.java    From james-project with Apache License 2.0 6 votes vote down vote up
/**
 * Adds header to the message
 */
@Override
public HookResult onMessage(SMTPSession session, Mail mail) {
    try {
        MimeMessage message = mail.getMessage();

        // Set the header name and value (supplied at init time).
        if (headerName != null) {
            message.setHeader(headerName, headerValue);
            message.saveChanges();
        }

    } catch (javax.mail.MessagingException me) {
        LOGGER.error(me.getMessage());
    }

    return HookResult.DECLINED;
}
 
Example 5
Source File: TestExtractEmailHeaders.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * NIFI-4326 adds a new feature to disable strict address parsing for
 * mailbox list header fields. This is a test case that asserts that
 * lax address parsing passes (when set to "strict=false") for malformed
 * addresses.
 */
@Test
public void testNonStrictParsingPassesForInvalidAddresses() throws Exception {
    final TestRunner runner = TestRunners.newTestRunner(new ExtractEmailHeaders());
    runner.setProperty(ExtractEmailHeaders.STRICT_PARSING, "false");

    MimeMessage simpleEmailMimeMessage = attachmentGenerator.SimpleEmailMimeMessage();

    simpleEmailMimeMessage.setHeader("From", "<bad_email>");
    simpleEmailMimeMessage.setHeader("To", "<>, Joe, \"\" <>");

    ByteArrayOutputStream messageBytes = new ByteArrayOutputStream();
    try {
        simpleEmailMimeMessage.writeTo(messageBytes);
    } catch (IOException | MessagingException e) {
        e.printStackTrace();
    }

    runner.enqueue(messageBytes.toByteArray());
    runner.run();

    runner.assertTransferCount(ExtractEmailHeaders.REL_SUCCESS, 1);
    runner.assertTransferCount(ExtractEmailHeaders.REL_FAILURE, 0);


    runner.assertQueueEmpty();
    final List<MockFlowFile> splits = runner.getFlowFilesForRelationship(ExtractEmailHeaders.REL_SUCCESS);
    splits.get(0).assertAttributeEquals("email.headers.from.0", "bad_email");
    splits.get(0).assertAttributeEquals("email.headers.to.0", "");
    splits.get(0).assertAttributeEquals("email.headers.to.1", "Joe");
    splits.get(0).assertAttributeEquals("email.headers.to.2", "");
}
 
Example 6
Source File: MimeMessageWrapperTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
public void testReplaceReturnPathOnBadMessage() throws Exception {
    MimeMessage message = getMessageWithBadReturnPath();
    message.setHeader(RFC2822Headers.RETURN_PATH, "<[email protected]>");
    Enumeration<String> e = message.getMatchingHeaderLines(new String[]{"Return-Path"});
    assertThat(e.nextElement()).isEqualTo("Return-Path: <[email protected]>");
    assertThat(e.hasMoreElements()).isFalse();
    Enumeration<String> h = message.getAllHeaderLines();
    assertThat(h.nextElement()).isEqualTo("Return-Path: <[email protected]>");
    assertThat(h.nextElement().startsWith("Return-Path:")).isFalse();
    LifecycleUtil.dispose(message);
}
 
Example 7
Source File: MimeMessageTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
/**
 * This test throw a NullPointerException when the original message was
 * created by a MimeMessageInputStreamSource.
 */
@Test
public void testMessageCloningViaCoWSubjectLost() throws Exception {
    MimeMessage mmorig = getSimpleMessage();

    MimeMessage mm = new MimeMessageCopyOnWriteProxy(mmorig);

    mm.setHeader("X-Test", "foo");
    mm.saveChanges();

    assertThat(getCleanedMessageSource(mm)).isEqualTo(getSimpleMessageCleanedSourceHeaderExpected());

    LifecycleUtil.dispose(mm);
    LifecycleUtil.dispose(mmorig);
}
 
Example 8
Source File: SerialiseToHTTP.java    From james-project with Apache License 2.0 5 votes vote down vote up
private void addHeader(Mail mail, boolean success, String errorMessage) {
    try {
        MimeMessage message = mail.getMessage();
        message.setHeader("X-toHTTP", (success ? "Succeeded" : "Failed"));
        if (!success && errorMessage != null && errorMessage.length() > 0) {
            message.setHeader("X-toHTTPFailure", errorMessage);
        }
        message.saveChanges();
    } catch (MessagingException me) {
        LOGGER.error("Messaging exception", me);
    }
}
 
Example 9
Source File: BayesianAnalysis.java    From james-project with Apache License 2.0 5 votes vote down vote up
/**
 * Saves changes resetting the original message id.
 */
private void saveChanges(MimeMessage message) throws MessagingException {
    String messageId = message.getMessageID();
    message.saveChanges();
    if (messageId != null) {
        message.setHeader(RFC2822Headers.MESSAGE_ID, messageId);
    }
}
 
Example 10
Source File: MessageContentTest.java    From subethasmtp with Apache License 2.0 5 votes vote down vote up
/** */
private void testEightBitMessage(String body, String charset) throws Exception
{
	MimeMessage message = new MimeMessage(this.session);
	message.addRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
	message.setFrom(new InternetAddress("[email protected]"));
	message.setSubject("hello");
	message.setText(body, charset);
	message.setHeader("Content-Transfer-Encoding", "8bit");

	Transport.send(message);
}
 
Example 11
Source File: DSNBounce.java    From james-project with Apache License 2.0 5 votes vote down vote up
private MimeMessage createBounceMessage(Mail originalMail) throws MessagingException {
    MimeMultipartReport multipart = createMultipart(originalMail);

    MimeMessage newMessage = new MimeMessage(Session.getDefaultInstance(System.getProperties(), null));
    newMessage.setContent(multipart);
    newMessage.setHeader(RFC2822Headers.CONTENT_TYPE, multipart.getContentType());
    return newMessage;
}
 
Example 12
Source File: DefaultMailService.java    From packagedrone with Eclipse Public License 1.0 5 votes vote down vote up
private Message createMessage ( final String to, final String subject ) throws MessagingException, AddressException
{
    final MimeMessage message = new MimeMessage ( this.session );

    final String from = getString ( "from" );
    if ( from != null )
    {
        message.setFrom ( new InternetAddress ( from ) );
    }
    else
    {
        message.setFrom ();
    }

    // recipient

    final InternetAddress recipient = new InternetAddress ();
    recipient.setAddress ( to );
    message.setRecipient ( javax.mail.Message.RecipientType.TO, recipient );

    // mail

    final String prefix = getString ( "prefix" );
    if ( prefix != null )
    {
        message.setSubject ( prefix + " " + subject );
    }
    else
    {
        message.setSubject ( subject );
    }

    message.setHeader ( "Return-Path", "<>" );

    return message;
}
 
Example 13
Source File: MimeMessageTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
public void testHeaderOrder() throws Exception {
    MimeMessage message = getSimpleMessage();
    message.setHeader(RFC2822Headers.RETURN_PATH, "<[email protected]>");
    Enumeration<String> h = message.getAllHeaderLines();

    assertThat("Return-Path: <[email protected]>").isEqualTo(h.nextElement());
    LifecycleUtil.dispose(message);
}
 
Example 14
Source File: EmailSmtpConnector.java    From mxisd with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void send(String senderAddress, String senderName, String recipient, String content) {
    if (StringUtils.isBlank(senderAddress)) {
        throw new FeatureNotAvailable("3PID Email identity: sender address is empty - " +
                "You must set a value for notifications to work");
    }

    if (StringUtils.isBlank(content)) {
        throw new InternalServerError("Notification content is empty");
    }

    try {
        InternetAddress sender = new InternetAddress(senderAddress, senderName);
        MimeMessage msg = new MimeMessage(session, IOUtils.toInputStream(content, StandardCharsets.UTF_8));

        // We must encode our headers ourselves as we have no guarantee that they were in the provided data.
        // This is required to support UTF-8 characters from user display names or room names in the subject header per example
        Enumeration<Header> headers = msg.getAllHeaders();
        while (headers.hasMoreElements()) {
            Header header = headers.nextElement();
            msg.setHeader(header.getName(), MimeUtility.encodeText(header.getValue()));
        }

        msg.setHeader("X-Mailer", MimeUtility.encodeText(Mxisd.Agent));
        msg.setSentDate(new Date());
        msg.setFrom(sender);
        msg.setRecipients(Message.RecipientType.TO, recipient);
        msg.saveChanges();

        log.info("Sending invite to {} via SMTP using {}:{}", recipient, cfg.getHost(), cfg.getPort());
        SMTPTransport transport = (SMTPTransport) session.getTransport("smtp");

        if (cfg.getTls() < 3) {
            transport.setStartTLS(cfg.getTls() > 0);
            transport.setRequireStartTLS(cfg.getTls() > 1);
        }

        log.info("Connecting to {}:{}", cfg.getHost(), cfg.getPort());
        if (StringUtils.isAllEmpty(cfg.getLogin(), cfg.getPassword())) {
            log.info("Not using SMTP authentication");
            transport.connect();
        } else {
            log.info("Using SMTP authentication");
            transport.connect(cfg.getLogin(), cfg.getPassword());
        }

        try {
            transport.sendMessage(msg, InternetAddress.parse(recipient));
            log.info("Invite to {} was sent", recipient);
        } finally {
            transport.close();
        }
    } catch (UnsupportedEncodingException | MessagingException e) {
        throw new RuntimeException("Unable to send e-mail invite to " + recipient, e);
    }
}
 
Example 15
Source File: DKIMSignTest.java    From james-project with Apache License 2.0 4 votes vote down vote up
@ParameterizedTest
@ValueSource(strings = {PKCS1_PEM_FILE, PKCS8_PEM_FILE})
void testDKIMSignMessageAsObjectConvertedTo7Bit(String pemFile)
        throws MessagingException, IOException, FailException {
    MimeMessage mm = new MimeMessage(Session
            .getDefaultInstance(new Properties()));
    mm.addFrom(new Address[]{new InternetAddress("[email protected]")});
    mm.addRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
    mm.setContent("An 8bit encoded body with €uro symbol.",
            "text/plain; charset=iso-8859-15");
    mm.setHeader("Content-Transfer-Encoding", "8bit");
    mm.saveChanges();

    FAKE_MAIL_CONTEXT.getServerInfo();

    FakeMailetConfig mci = FakeMailetConfig.builder()
            .mailetName("Test")
            .mailetContext(FAKE_MAIL_CONTEXT)
            .setProperty(
                    "signatureTemplate",
                    "v=1; s=selector; d=example.com; h=from:to:received:received; a=rsa-sha256; bh=; b=;")
            .setProperty("privateKeyFilepath", pemFile)
            .build();

    Mail mail = FakeMail.builder()
        .name("test")
        .mimeMessage(mm)
        .build();

    Mailet mailet = new DKIMSign();
    mailet.init(mci);

    Mailet m7bit = new ConvertTo7Bit();
    m7bit.init(mci);
    m7bit.service(mail);

    mailet.service(mail);

    m7bit.service(mail);

    ByteArrayOutputStream rawMessage = new ByteArrayOutputStream();
    mail.getMessage().writeTo(rawMessage);

    MockPublicKeyRecordRetriever mockPublicKeyRecordRetriever = new MockPublicKeyRecordRetriever(
            "v=DKIM1; k=rsa; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDYDaYKXzwVYwqWbLhmuJ66aTAN8wmDR+rfHE8HfnkSOax0oIoTM5zquZrTLo30870YMfYzxwfB6j/Nz3QdwrUD/t0YMYJiUKyWJnCKfZXHJBJ+yfRHr7oW+UW3cVo9CG2bBfIxsInwYe175g9UjyntJpWueqdEIo1c2bhv9Mp66QIDAQAB;",
            "selector", "example.com");
    verify(rawMessage, mockPublicKeyRecordRetriever);
}
 
Example 16
Source File: DKIMSignTest.java    From james-project with Apache License 2.0 4 votes vote down vote up
@ParameterizedTest
@ValueSource(strings = {PKCS1_PEM_FILE, PKCS8_PEM_FILE})
void testDKIMSignMessageAsObjectNotConverted(String pemFile)
        throws MessagingException, IOException, FailException {
    MimeMessage mm = new MimeMessage(Session
            .getDefaultInstance(new Properties()));
    mm.addFrom(new Address[]{new InternetAddress("[email protected]")});
    mm.addRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
    mm.setContent("An 8bit encoded body with €uro symbol.",
            "text/plain; charset=iso-8859-15");
    mm.setHeader("Content-Transfer-Encoding", "8bit");
    mm.saveChanges();

    FAKE_MAIL_CONTEXT.getServerInfo();

    FakeMailetConfig mci = FakeMailetConfig.builder()
            .mailetName("Test")
            .mailetContext(FAKE_MAIL_CONTEXT)
            .setProperty(
                    "signatureTemplate",
                    "v=1; s=selector; d=example.com; h=from:to:received:received; a=rsa-sha256; bh=; b=;")
            .setProperty("privateKeyFilepath", pemFile)
            .build();

    Mail mail = FakeMail.builder()
        .name("test")
        .mimeMessage(mm)
        .build();

    Mailet mailet = new DKIMSign();
    mailet.init(mci);

    Mailet m7bit = new ConvertTo7Bit();
    m7bit.init(mci);
    // m7bit.service(mail);

    mailet.service(mail);

    m7bit.service(mail);

    ByteArrayOutputStream rawMessage = new ByteArrayOutputStream();
    mail.getMessage().writeTo(rawMessage);

    MockPublicKeyRecordRetriever mockPublicKeyRecordRetriever = new MockPublicKeyRecordRetriever(
            "v=DKIM1; k=rsa; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDYDaYKXzwVYwqWbLhmuJ66aTAN8wmDR+rfHE8HfnkSOax0oIoTM5zquZrTLo30870YMfYzxwfB6j/Nz3QdwrUD/t0YMYJiUKyWJnCKfZXHJBJ+yfRHr7oW+UW3cVo9CG2bBfIxsInwYe175g9UjyntJpWueqdEIo1c2bhv9Mp66QIDAQAB;",
            "selector", "example.com");
    try {
        verify(rawMessage, mockPublicKeyRecordRetriever);
        fail("Expected PermFail");
    } catch (PermFailException e) {
        // do nothing
    }
}
 
Example 17
Source File: AbstractSign.java    From james-project with Apache License 2.0 4 votes vote down vote up
/**
 * Service does the hard work, and signs
 *
 * @param mail the mail to sign
 * @throws MessagingException if a problem arises signing the mail
 */
@Override
public void service(Mail mail) throws MessagingException {
    
    try {
        if (!isOkToSign(mail)) {
            return;
        }
        
        MimeBodyPart wrapperBodyPart = getWrapperBodyPart(mail);
        
        MimeMessage originalMessage = mail.getMessage();
        
        // do it
        MimeMultipart signedMimeMultipart;
        if (wrapperBodyPart != null) {
            signedMimeMultipart = getKeyHolder().generate(wrapperBodyPart);
        } else {
            signedMimeMultipart = getKeyHolder().generate(originalMessage);
        }
        
        MimeMessage newMessage = new MimeMessage(Session.getDefaultInstance(System.getProperties(),
        null));
        Enumeration<String> headerEnum = originalMessage.getAllHeaderLines();
        while (headerEnum.hasMoreElements()) {
            newMessage.addHeaderLine(headerEnum.nextElement());
        }
        
        newMessage.setSender(new InternetAddress(getKeyHolder().getSignerAddress(), getSignerName()));
  
        if (isRebuildFrom()) {
            // builds a new "mixed" "From:" header
            InternetAddress modifiedFromIA = new InternetAddress(getKeyHolder().getSignerAddress(), mail.getMaybeSender().asString());
            newMessage.setFrom(modifiedFromIA);
            
            // if the original "ReplyTo:" header is missing sets it to the original "From:" header
            newMessage.setReplyTo(originalMessage.getReplyTo());
        }
        
        newMessage.setContent(signedMimeMultipart, signedMimeMultipart.getContentType());
        String messageId = originalMessage.getMessageID();
        newMessage.saveChanges();
        if (messageId != null) {
            newMessage.setHeader(RFC2822Headers.MESSAGE_ID, messageId);
        }
        
        mail.setMessage(newMessage);
        
        // marks this mail as server-signed
        mail.setAttribute(new Attribute(SMIMEAttributeNames.SMIME_SIGNING_MAILET, AttributeValue.of(this.getClass().getName())));
        // it is valid for us by definition (signed here by us)
        mail.setAttribute(new Attribute(SMIMEAttributeNames.SMIME_SIGNATURE_VALIDITY, AttributeValue.of("valid")));
        
        // saves the trusted server signer address
        // warning: should be same as the mail address in the certificate, but it is not guaranteed
        mail.setAttribute(new Attribute(SMIMEAttributeNames.SMIME_SIGNER_ADDRESS, AttributeValue.of(getKeyHolder().getSignerAddress())));
        
        if (isDebug()) {
            LOGGER.debug("Message signed, reverse-path: {}, Id: {}", mail.getMaybeSender().asString(), messageId);
        }
        
    } catch (MessagingException me) {
        LOGGER.error("MessagingException found - could not sign!", me);
        throw me;
    } catch (Exception e) {
        LOGGER.error("Exception found", e);
        throw new MessagingException("Exception thrown - could not sign!", e);
    }
    
}
 
Example 18
Source File: BayesianAnalysis.java    From james-project with Apache License 2.0 4 votes vote down vote up
/**
 * Scans the mail and determines the spam probability.
 * 
 * @param mail
 *            The Mail message to be scanned.
 * @throws MessagingException
 *             if a problem arises
 */
@Override
public void service(Mail mail) throws MessagingException {

    try {
        MimeMessage message = mail.getMessage();

        if (ignoreLocalSender && isSenderLocal(mail)) {
            // ignore the message if the sender is local
            return;
        }

        String[] headerArray = message.getHeader(headerName);
        // ignore the message if already analyzed
        if (headerArray != null && headerArray.length > 0) {
            return;
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        double probability;

        if (message.getSize() < getMaxSize()) {
            message.writeTo(baos);
            probability = analyzer.computeSpamProbability(new BufferedReader(new StringReader(baos.toString())));
        } else {
            probability = 0.0;
        }

        mail.setAttribute(new Attribute(MAIL_ATTRIBUTE_NAME, AttributeValue.of(probability)));
        message.setHeader(headerName, Double.toString(probability));

        DecimalFormat probabilityForm = (DecimalFormat) DecimalFormat.getInstance();
        probabilityForm.applyPattern("##0.##%");
        String probabilityString = probabilityForm.format(probability);

        String senderString = mail.getMaybeSender().asString("null");
        if (probability > 0.1) {
            final Collection<MailAddress> recipients = mail.getRecipients();
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(headerName + ": " + probabilityString + "; From: " + senderString + "; Recipient(s): " + getAddressesString(recipients));
            }

            // Check if we should tag the subject
            if (tagSubject) {
                appendToSubject(message, " [" + probabilityString + (probability > 0.9 ? " SPAM" : " spam") + "]");
            }
        }

        saveChanges(message);

    } catch (Exception e) {
        LOGGER.error("Exception: {}", e.getMessage(), e);
        throw new MessagingException("Exception thrown", e);
    }
}
 
Example 19
Source File: WhiteListManager.java    From james-project with Apache License 2.0 4 votes vote down vote up
private void sendReplyFromPostmaster(Mail mail, String stringContent) {
    try {
        MailAddress notifier = getMailetContext().getPostmaster();

        MailAddress senderMailAddress = mail.getMaybeSender().get();

        MimeMessage message = mail.getMessage();
        // Create the reply message
        MimeMessage reply = new MimeMessage(Session.getDefaultInstance(System.getProperties(), null));

        // Create the list of recipients in the Address[] format
        InternetAddress[] rcptAddr = new InternetAddress[1];
        rcptAddr[0] = senderMailAddress.toInternetAddress();
        reply.setRecipients(Message.RecipientType.TO, rcptAddr);

        // Set the sender...
        reply.setFrom(notifier.toInternetAddress());

        // Create the message body
        MimeMultipart multipart = new MimeMultipart();
        // Add message as the first mime body part
        MimeBodyPart part = new MimeBodyPart();
        part.setContent(stringContent, "text/plain");
        part.setHeader(RFC2822Headers.CONTENT_TYPE, "text/plain");
        multipart.addBodyPart(part);

        reply.setContent(multipart);
        reply.setHeader(RFC2822Headers.CONTENT_TYPE, multipart.getContentType());

        // Create the list of recipients in our MailAddress format
        Set<MailAddress> recipients = new HashSet<>();
        recipients.add(senderMailAddress);

        // Set additional headers
        if (reply.getHeader(RFC2822Headers.DATE) == null) {
            reply.setHeader(RFC2822Headers.DATE, DateFormats.RFC822_DATE_FORMAT.format(LocalDateTime.now()));
        }
        String subject = message.getSubject();
        if (subject == null) {
            subject = "";
        }
        if (subject.indexOf("Re:") == 0) {
            reply.setSubject(subject);
        } else {
            reply.setSubject("Re:" + subject);
        }
        reply.setHeader(RFC2822Headers.IN_REPLY_TO, message.getMessageID());

        // Send it off...
        getMailetContext().sendMail(notifier, recipients, reply);
    } catch (Exception e) {
        LOGGER.error("Exception found sending reply", e);
    }
}
 
Example 20
Source File: AddHabeasWarrantMark.java    From james-project with Apache License 2.0 3 votes vote down vote up
/**
 * Called by the mailet container to allow the mailet to process to
 * a message message.
 *
 * This method adds the Habeas Warrant Mark headers to the message,
 * saves the changes, and then allows the message to fall through
 * in the pipeline.
 *
 * @param mail - the Mail object that contains the message and routing information
 * @throws javax.mail.MessagingException - if an message or address parsing exception occurs or
 *      an exception that interferes with the mailet's normal operation
 */
@Override
public void service(Mail mail) throws MessagingException {
    MimeMessage message = mail.getMessage();

    for (int i = 0; i < HasHabeasWarrantMark.warrantMark.length; i++) {
        message.setHeader(HasHabeasWarrantMark.warrantMark[i][0], HasHabeasWarrantMark.warrantMark[i][1]);
    }

    message.saveChanges();
}