Example usage for javax.mail.internet MimeMessage saveChanges

List of usage examples for javax.mail.internet MimeMessage saveChanges

Introduction

In this page you can find the example usage for javax.mail.internet MimeMessage saveChanges.

Prototype

@Override
public void saveChanges() throws MessagingException 

Source Link

Document

Updates the appropriate header fields of this message to be consistent with the message's contents.

Usage

From source file:mitm.application.djigzo.james.mailets.RequestSenderCertificateTest.java

@Test
public void testRequestCertificateMultiThreaded() throws Exception {
    MockMailetConfig mailetConfig = new MockMailetConfig();

    final RequestSenderCertificate mailet = new RequestSenderCertificate();

    mailet.init(mailetConfig);/*from  www  .  j ava 2 s .co m*/

    final MimeMessage message1 = new MimeMessage(MailSession.getDefaultSession());

    message1.setContent("test", "text/plain");
    message1.setFrom(new InternetAddress("from@example.com"));

    final Collection<MailAddress> recipients = new LinkedList<MailAddress>();

    recipients.add(new MailAddress("to@example.com"));

    message1.saveChanges();

    final MimeMessage message2 = new MimeMessage(MailSession.getDefaultSession());

    message2.setContent("test", "text/plain");
    message2.setFrom(new InternetAddress("from2@example.com"));

    Callable<Null> callable = new Callable<Null>() {

        @Override
        public Null call() throws Exception {
            MockMail mail1 = new MockMail();

            mail1.setMessage(message1);

            mail1.setRecipients(recipients);

            mail1.setSender(new MailAddress("sender1@example.com"));

            mailet.service(mail1);

            MockMail mail2 = new MockMail();

            mail2.setMessage(message2);

            mail2.setRecipients(recipients);

            mail2.setSender(new MailAddress("sender2@example.com"));

            mailet.service(mail2);

            return null;
        }
    };

    Collection<Future<?>> futures = new LinkedList<Future<?>>();

    for (int i = 0; i < 20; i++) {
        futures.add(executorService.submit(callable));
    }

    for (Future<?> future : futures) {
        future.get();
    }

    assertEquals(INITIAL_KEY_STORE_SIZE + 2, proxy.getKeyAndCertStoreSize());
}

From source file:mail.MailService.java

/**
 * Erstellt eine MIME-Mail inkl. Transfercodierung.
 * @param email/*w w w .  ja  va  2  s.  com*/
 * @throws MessagingException
 * @throws IOException
 */
public String createMail3(Mail email, Config config) throws MessagingException, IOException {

    byte[] mailAsBytes = email.getText();
    byte[] outputBytes;

    // Transfercodierung anwenden
    if (config.getTranscodeDescription().equals(Config.BASE64)) {
        outputBytes = encodeBase64(mailAsBytes);
    } else if (config.getTranscodeDescription().equals(Config.QP)) {
        outputBytes = encodeQuotedPrintable(mailAsBytes);
    } else {
        outputBytes = mailAsBytes;
    }
    email.setText(outputBytes);

    Properties props = new Properties();
    props.put("mail.smtp.host", "mail.java-tutor.com");
    Session session = Session.getDefaultInstance(props);

    MimeMessage msg = new MimeMessage(session);
    //      msg.setHeader("MIME-Version" , "1.0"); 
    //      msg.setHeader("Content-Type" , "text/plain"); 

    // Absender
    InternetAddress addressFrom = new InternetAddress(email.getAbsender());
    msg.setFrom(addressFrom);

    // Empfnger
    InternetAddress addressTo = new InternetAddress(email.getEmpfaenger());
    msg.setRecipient(Message.RecipientType.TO, addressTo);

    msg.setSubject(email.getBetreff());
    msg.setSentDate(email.getAbsendeDatum());

    msg.setText(Utils.toString(outputBytes));
    msg.saveChanges();

    // Mail in Ausgabestrom schreiben
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    try {
        msg.writeTo(bOut);
    } catch (IOException e) {
        System.out.println("Fehler beim Schreiben der Mail in Schritt 3");
        throw e;
    }

    //      String out = bOut.toString();
    //       int pos1 = out.indexOf("Message-ID");
    //       int pos2 = out.indexOf("@localhost") + 13;
    //       String output = out.subSequence(0, pos1).toString();
    //       output += (out.substring(pos2));

    return removeMessageId(bOut.toString().replaceAll(ITexte.CONTENT,
            "Content-Transfer-Encoding: " + config.getTranscodeDescription()));
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskSMWar.CFAsteriskSMWarRequestResetPasswordHtml.java

protected void sendPasswordResetEMail(HttpServletRequest request, ICFSecuritySecUserObj resetUser,
        ICFSecurityClusterObj cluster) throws AddressException, MessagingException, NamingException {

    final String S_ProcName = "sendPasswordResetEMail";

    Properties props = System.getProperties();
    String clusterDescription = cluster.getRequiredDescription();

    Context ctx = new InitialContext();

    String smtpEmailFrom = (String) ctx.lookup("java:comp/env/CFAsterisk24SmtpEmailFrom");
    if ((smtpEmailFrom == null) || (smtpEmailFrom.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAsterisk24SmtpEmailFrom");
    }/* w  w w .j  a  v a 2 s  .c o  m*/

    smtpUsername = (String) ctx.lookup("java:comp/env/CFAsterisk24SmtpUsername");
    if ((smtpUsername == null) || (smtpUsername.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAsterisk24SmtpUsername");
    }

    smtpPassword = (String) ctx.lookup("java:comp/env/CFAsterisk24SmtpPassword");
    if ((smtpPassword == null) || (smtpPassword.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAsterisk24SmtpPassword");
    }

    Session emailSess = Session.getInstance(props, new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(smtpUsername, smtpPassword);
        }
    });

    String thisURI = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + request.getRequestURI().toString();
    int lastSlash = thisURI.lastIndexOf('/');
    String baseURI = thisURI.substring(0, lastSlash);
    UUID resetUUID = resetUser.getOptionalPasswordResetUuid();

    String msgBody = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n" + "<HTML>\n" + "<BODY>\n"
            + "<p>\n" + "You requested a password reset for " + resetUser.getRequiredEMailAddress()
            + " used for accessing " + clusterDescription + ".\n" + "<p>"
            + "Please click on the following link to reset your password:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAsteriskSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI
            + "/CFAsteriskSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "<p>"
            + "Or click on the following link to cancel the reset request:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAsteriskSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI
            + "/CFAsteriskSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n"
            + "</BODY>\n" + "</HTML>\n";

    MimeMessage msg = new MimeMessage(emailSess);
    msg.setFrom(new InternetAddress(smtpEmailFrom));
    InternetAddress mailTo[] = InternetAddress.parse(resetUser.getRequiredEMailAddress(), false);
    msg.setRecipient(Message.RecipientType.TO, mailTo[0]);
    msg.setSubject("You requested a password reset for your account with " + clusterDescription + "?");
    msg.setContent(msgBody, "text/html");
    msg.setSentDate(new Date());
    msg.saveChanges();

    Transport.send(msg);
}

From source file:com.anteam.alert.email.service.EmailAntlert.java

@Override
public boolean send(AntlertMessage antlertMsg) {

    MimeMessage mimeMsg; // MIME

    // from?to?//  w w  w. j a va2s  .co m
    mimeMsg = new javax.mail.internet.MimeMessage(mailSession);

    try {
        // ?
        mimeMsg.setFrom(sender);
        // 
        mimeMsg.setRecipients(RecipientType.TO, receivers);
        // 
        mimeMsg.setSubject(antlertMsg.getTitle(), CHARSET);

        // 
        MimeBodyPart messageBody = new MimeBodyPart();
        messageBody.setContent(antlertMsg.getContent(), CONTENT_MIME_TYPE);

        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBody);
        mimeMsg.setContent(multipart);

        // ??
        mimeMsg.setSentDate(new Date());
        mimeMsg.saveChanges();

        // ??
        Transport.send(mimeMsg);
    } catch (MessagingException e) {
        logger.error("???", e);
        return false;
    }
    return true;
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_2.CFAstSMWar.CFAstSMWarRequestResetPasswordHtml.java

protected void sendPasswordResetEMail(HttpServletRequest request, ICFAstSecUserObj resetUser,
        ICFAstClusterObj cluster) throws AddressException, MessagingException, NamingException {

    final String S_ProcName = "sendPasswordResetEMail";

    Properties props = System.getProperties();
    String clusterDescription = cluster.getRequiredDescription();

    Context ctx = new InitialContext();

    String smtpEmailFrom = (String) ctx.lookup("java:comp/env/CFAst22SmtpEmailFrom");
    if ((smtpEmailFrom == null) || (smtpEmailFrom.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAst22SmtpEmailFrom");
    }//from   www . ja  v a  2 s . c o m

    smtpUsername = (String) ctx.lookup("java:comp/env/CFAst22SmtpUsername");
    if ((smtpUsername == null) || (smtpUsername.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAst22SmtpUsername");
    }

    smtpPassword = (String) ctx.lookup("java:comp/env/CFAst22SmtpPassword");
    if ((smtpPassword == null) || (smtpPassword.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAst22SmtpPassword");
    }

    Session emailSess = Session.getInstance(props, new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(smtpUsername, smtpPassword);
        }
    });

    String thisURI = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + request.getRequestURI().toString();
    int lastSlash = thisURI.lastIndexOf('/');
    String baseURI = thisURI.substring(0, lastSlash);
    UUID resetUUID = resetUser.getOptionalPasswordResetUuid();

    String msgBody = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n" + "<HTML>\n" + "<BODY>\n"
            + "<p>\n" + "You requested a password reset for " + resetUser.getRequiredEMailAddress()
            + " used for accessing " + clusterDescription + ".\n" + "<p>"
            + "Please click on the following link to reset your password:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAstSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI
            + "/CFAstSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "<p>"
            + "Or click on the following link to cancel the reset request:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAstSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI
            + "/CFAstSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "</BODY>\n"
            + "</HTML>\n";

    MimeMessage msg = new MimeMessage(emailSess);
    msg.setFrom(new InternetAddress(smtpEmailFrom));
    InternetAddress mailTo[] = InternetAddress.parse(resetUser.getRequiredEMailAddress(), false);
    msg.setRecipient(Message.RecipientType.TO, mailTo[0]);
    msg.setSubject("You requested a password reset for your account with " + clusterDescription + "?");
    msg.setContent(msgBody, "text/html");
    msg.setSentDate(new Date());
    msg.saveChanges();

    Transport.send(msg);
}

From source file:mitm.application.djigzo.james.mailets.SMIMEEncryptTest.java

@Test
public void testMultipartWithIllegalContentTransferEncoding() throws Exception {
    MockMailetConfig mailetConfig = new MockMailetConfig("test");

    mailetConfig.setInitParameter("algorithm", "AES128");

    SMIMEEncrypt mailet = new SMIMEEncrypt();

    mailet.init(mailetConfig);/*from w  w w  . j  a v  a  2s .c o m*/

    Mail mail = new MockMail();

    MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/quoted-printable-multipart.eml"));

    assertTrue(message.isMimeType("multipart/mixed"));

    MimeMultipart mp = (MimeMultipart) message.getContent();

    assertEquals(2, mp.getCount());

    BodyPart part = mp.getBodyPart(0);

    assertTrue(part.isMimeType("text/plain"));
    assertEquals("==", (String) part.getContent());

    mail.setMessage(message);

    Set<MailAddress> recipients = new HashSet<MailAddress>();

    recipients.add(new MailAddress("test@example.com"));

    mail.setRecipients(recipients);

    DjigzoMailAttributes mailAttributes = new DjigzoMailAttributesImpl(mail);

    mailAttributes.setCertificates(certificates);

    mailet.service(mail);

    MailUtils.validateMessage(mail.getMessage());

    KeyStoreKeyProvider keyStore = new KeyStoreKeyProvider(
            loadKeyStore(new File("test/resources/testdata/keys/testCertificates.p12"), "test"), "test");

    SMIMEInspector inspector = new SMIMEInspectorImpl(mail.getMessage(), keyStore, "BC");

    assertEquals(SMIMEType.ENCRYPTED, inspector.getSMIMEType());
    assertEquals(SMIMEEncryptionAlgorithm.AES128_CBC.getOID().toString(),
            inspector.getEnvelopedInspector().getEncryptionAlgorithmOID());
    assertEquals(20, inspector.getEnvelopedInspector().getRecipients().size());

    MimeMessage decrypted = inspector.getContentAsMimeMessage();

    decrypted.saveChanges();

    assertNotNull(decrypted);

    MailUtils.writeMessage(decrypted, new File(tempDir, "testMultipartWithIllegalContentTransferEncoding.eml"));

    assertTrue(decrypted.isMimeType("multipart/mixed"));

    mp = (MimeMultipart) decrypted.getContent();

    assertEquals(2, mp.getCount());

    part = mp.getBodyPart(0);

    assertTrue(part.isMimeType("text/plain"));

    /*
     * The body should not be changed to =3D=3D because the body should not be quoted-printable encoded
     * again
     */
    assertEquals("==", (String) part.getContent());
}

From source file:mitm.application.djigzo.james.mailets.SMIMEEncryptTest.java

@Test
public void testCurruptMessage() throws Exception {
    MockMailetConfig mailetConfig = new MockMailetConfig("test");

    SMIMEEncrypt mailet = new SMIMEEncrypt();

    mailet.init(mailetConfig);/* www .  j a v  a 2 s  . c om*/

    Mail mail = new MockMail();

    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    MimeBodyPart emptyPart = new MimeBodyPart();

    message.setContent(emptyPart, "text/plain");

    message.saveChanges();

    mail.setMessage(message);

    Set<MailAddress> recipients = new HashSet<MailAddress>();

    recipients.add(new MailAddress("test@example.com"));

    mail.setRecipients(recipients);

    DjigzoMailAttributes mailAttributes = new DjigzoMailAttributesImpl(mail);

    mailAttributes.setCertificates(certificates);

    mailet.service(mail);

    assertEquals(message, mail.getMessage());

    try {
        MailUtils.validateMessage(message);

        fail();
    } catch (IOException e) {
        // expected. The message should be corrupt
    }
}

From source file:com.stimulus.archiva.store.MessageStore.java

public void saveEmailChanges(MimeMessage message) throws MessagingException {
    logger.debug("saveEmailChanges");
    String[] messageId = message.getHeader("Message-Id");
    //try { System.out.println("Content:"+message.getContent()); } catch (Exception e) {}
    message.saveChanges();
    if (messageId != null && messageId.length > 0)
        message.setHeader("Message-Id", messageId[0]);
}

From source file:mitm.application.djigzo.james.mailets.SMIMESignTest.java

@Test
public void testInvalidFrom() throws Exception {
    MockMailetConfig mailetConfig = new MockMailetConfig("test");

    mailetConfig.setInitParameter("catchRuntimeExceptions", "false");

    SMIMESign mailet = new SMIMESign();

    mailet.init(mailetConfig);/* ww w .j a  va  2s  . c om*/

    MockMail mail = new MockMail();

    MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/simple-text-message.eml"));

    message.setFrom(new InternetAddress("xxx"));

    message.saveChanges();

    mail.setMessage(message);

    Set<MailAddress> recipients = new HashSet<MailAddress>();

    recipients.add(new MailAddress("m.brinkers@pobox.com"));

    mail.setRecipients(recipients);

    mail.setSender(null);

    mailet.service(mail);

    MailUtils.validateMessage(mail.getMessage());

    SMIMEInspector inspector = new SMIMEInspectorImpl(mail.getMessage(), null, "BC");

    assertEquals(SMIMEType.NONE, inspector.getSMIMEType());
}