Search in sources :

Example 1 with Session

use of javax.mail.Session in project jetty.project by eclipse.

the class TestMailSessionReference method testMailSessionReference.

@Test
public void testMailSessionReference() throws Exception {
    InitialContext icontext = new InitialContext();
    MailSessionReference sref = new MailSessionReference();
    sref.setUser("janb");
    sref.setPassword("OBF:1xmk1w261z0f1w1c1xmq");
    Properties props = new Properties();
    props.put("mail.smtp.host", "xxx");
    props.put("mail.debug", "true");
    sref.setProperties(props);
    NamingUtil.bind(icontext, "mail/Session", sref);
    Object x = icontext.lookup("mail/Session");
    assertNotNull(x);
    assertTrue(x instanceof javax.mail.Session);
    javax.mail.Session session = (javax.mail.Session) x;
    Properties sessionProps = session.getProperties();
    assertEquals(props, sessionProps);
    assertTrue(session.getDebug());
    Context foo = icontext.createSubcontext("foo");
    NameParser parser = icontext.getNameParser("");
    Name objectNameInNamespace = parser.parse(icontext.getNameInNamespace());
    objectNameInNamespace.addAll(parser.parse("mail/Session"));
    NamingUtil.bind(foo, "mail/Session", new LinkRef(objectNameInNamespace.toString()));
    Object o = foo.lookup("mail/Session");
    assertNotNull(o);
    Session fooSession = (Session) o;
    assertEquals(props, fooSession.getProperties());
    assertTrue(fooSession.getDebug());
    icontext.destroySubcontext("mail");
    icontext.destroySubcontext("foo");
}
Also used : InitialContext(javax.naming.InitialContext) Context(javax.naming.Context) Session(javax.mail.Session) Properties(java.util.Properties) InitialContext(javax.naming.InitialContext) NameParser(javax.naming.NameParser) Session(javax.mail.Session) Name(javax.naming.Name) LinkRef(javax.naming.LinkRef) Test(org.junit.Test)

Example 2 with Session

use of javax.mail.Session in project Openfire by igniterealtime.

the class SendMail method sendMessage.

public boolean sendMessage(String message, String host, String port, String username, String password) {
    boolean ok = false;
    String uidString = "";
    try {
        // Set the email properties necessary to send email
        final Properties props = System.getProperties();
        props.put("mail.smtp.host", host);
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.server", host);
        if (ModelUtil.hasLength(port)) {
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", port);
        }
        Session sess;
        if (ModelUtil.hasLength(password) && ModelUtil.hasLength(username)) {
            sess = Session.getInstance(props, new MailAuthentication(username, password));
        } else {
            sess = Session.getDefaultInstance(props, null);
        }
        Message msg = new MimeMessage(sess);
        StringTokenizer toST = new StringTokenizer(toField, ",");
        if (toST.countTokens() > 1) {
            InternetAddress[] address = new InternetAddress[toST.countTokens()];
            int addrIndex = 0;
            String addrString = "";
            while (toST.hasMoreTokens()) {
                addrString = toST.nextToken();
                address[addrIndex] = (new InternetAddress(addrString));
                addrIndex = addrIndex + 1;
            }
            msg.setRecipients(Message.RecipientType.TO, address);
        } else {
            InternetAddress[] address = { new InternetAddress(toField) };
            msg.setRecipients(Message.RecipientType.TO, address);
        }
        InternetAddress from = new InternetAddress(myAddress);
        msg.setFrom(from);
        msg.setSubject(subjectField);
        UID msgUID = new UID();
        uidString = msgUID.toString();
        msg.setHeader("X-Mailer", uidString);
        msg.setSentDate(new Date());
        MimeMultipart mp = new MimeMultipart();
        // create body part for textarea
        MimeBodyPart mbp1 = new MimeBodyPart();
        if (getCustomerName() != null) {
            messageText = "From: " + getCustomerName() + "\n" + messageText;
        }
        if (isHTML) {
            mbp1.setContent(messageText, "text/html");
        } else {
            mbp1.setContent(messageText, "text/plain");
        }
        mp.addBodyPart(mbp1);
        try {
            if (!isHTML) {
                msg.setContent(messageText, "text/plain");
            } else {
                msg.setContent(messageText, "text/html");
            }
            Transport.send(msg);
            ok = true;
        } catch (SendFailedException sfe) {
            Log.warn("Could not connect to SMTP server.");
        }
    } catch (Exception eq) {
        Log.warn("Could not connect to SMTP server.");
    }
    return ok;
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) SendFailedException(javax.mail.SendFailedException) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) Properties(java.util.Properties) Date(java.util.Date) SendFailedException(javax.mail.SendFailedException) UID(java.rmi.server.UID) StringTokenizer(java.util.StringTokenizer) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) MimeBodyPart(javax.mail.internet.MimeBodyPart) Session(javax.mail.Session)

Example 3 with Session

use of javax.mail.Session in project camel by apache.

the class MailConfiguration method createJavaMailSender.

protected JavaMailSender createJavaMailSender() {
    JavaMailSender answer = new DefaultJavaMailSender();
    if (javaMailProperties != null) {
        answer.setJavaMailProperties(javaMailProperties);
    } else {
        // set default properties if none provided
        answer.setJavaMailProperties(createJavaMailProperties());
        // add additional properties if provided
        if (additionalJavaMailProperties != null) {
            answer.getJavaMailProperties().putAll(additionalJavaMailProperties);
        }
    }
    if (host != null) {
        answer.setHost(host);
    }
    if (port >= 0) {
        answer.setPort(port);
    }
    if (username != null) {
        answer.setUsername(username);
    }
    if (password != null) {
        answer.setPassword(password);
    }
    if (protocol != null) {
        answer.setProtocol(protocol);
    }
    if (session != null) {
        answer.setSession(session);
    } else {
        ClassLoader tccl = Thread.currentThread().getContextClassLoader();
        try {
            if (applicationClassLoader != null) {
                Thread.currentThread().setContextClassLoader(applicationClassLoader);
            }
            // use our authenticator that does no live user interaction but returns the already configured username and password
            Session session = Session.getInstance(answer.getJavaMailProperties(), new DefaultAuthenticator(getUsername(), getPassword()));
            // sets the debug mode of the underlying mail framework
            session.setDebug(debugMode);
            answer.setSession(session);
        } finally {
            Thread.currentThread().setContextClassLoader(tccl);
        }
    }
    return answer;
}
Also used : Session(javax.mail.Session)

Example 4 with Session

use of javax.mail.Session in project camel by apache.

the class MailProducerTest method testProducerBodyIsMimeMessage.

@Test
public void testProducerBodyIsMimeMessage() throws Exception {
    Mailbox.clearAll();
    getMockEndpoint("mock:result").expectedMessageCount(1);
    Address from = new InternetAddress("fromCamelTest@localhost");
    Address to = new InternetAddress("recipient2@localhost");
    Session session = Session.getDefaultInstance(System.getProperties());
    MimeMessage mimeMessage = new MimeMessage(session);
    mimeMessage.setFrom(from);
    mimeMessage.addRecipient(RecipientType.TO, to);
    mimeMessage.setSubject("This is the subject.");
    mimeMessage.setText("This is the message");
    template.sendBodyAndHeader("direct:start", mimeMessage, "To", "someone@localhost");
    assertMockEndpointsSatisfied();
    // need to check the message header
    Exchange exchange = getMockEndpoint("mock:result").getExchanges().get(0);
    assertNotNull("The message id should not be null", exchange.getIn().getHeader(MailConstants.MAIL_MESSAGE_ID));
    Mailbox box = Mailbox.get("someone@localhost");
    assertEquals(0, box.size());
    // Check if the mimeMessagea has override body and headers
    Mailbox box2 = Mailbox.get("recipient2@localhost");
    assertEquals(1, box2.size());
}
Also used : Exchange(org.apache.camel.Exchange) InternetAddress(javax.mail.internet.InternetAddress) Address(javax.mail.Address) InternetAddress(javax.mail.internet.InternetAddress) Mailbox(org.jvnet.mock_javamail.Mailbox) MimeMessage(javax.mail.internet.MimeMessage) Session(javax.mail.Session) Test(org.junit.Test)

Example 5 with Session

use of javax.mail.Session in project camel by apache.

the class MimeMessageConsumeTest method testSendAndReceiveMails.

@Test
public void testSendAndReceiveMails() throws Exception {
    Mailbox.clearAll();
    MockEndpoint resultEndpoint = getMockEndpoint("mock:result");
    resultEndpoint.expectedMinimumMessageCount(1);
    Properties properties = new Properties();
    properties.put("mail.smtp.host", "localhost");
    Session session = Session.getInstance(properties, null);
    MimeMessage message = new MimeMessage(session);
    populateMimeMessageBody(message);
    message.setRecipients(Message.RecipientType.TO, "james3@localhost");
    Transport.send(message);
    // lets test the receive worked
    resultEndpoint.assertIsSatisfied();
    Exchange exchange = resultEndpoint.getReceivedExchanges().get(0);
    String text = exchange.getIn().getBody(String.class);
    assertEquals("mail body", body, text);
    assertNotNull("attachments got lost", exchange.getIn().getAttachments());
    for (String s : exchange.getIn().getAttachmentNames()) {
        DataHandler dh = exchange.getIn().getAttachment(s);
        Object content = dh.getContent();
        assertNotNull("Content should not be empty", content);
        assertEquals("log4j2.properties", dh.getName());
    }
}
Also used : Exchange(org.apache.camel.Exchange) MockEndpoint(org.apache.camel.component.mock.MockEndpoint) MimeMessage(javax.mail.internet.MimeMessage) DataHandler(javax.activation.DataHandler) Properties(java.util.Properties) Session(javax.mail.Session) Test(org.junit.Test)

Aggregations

Session (javax.mail.Session)343 MimeMessage (javax.mail.internet.MimeMessage)240 Properties (java.util.Properties)229 InternetAddress (javax.mail.internet.InternetAddress)170 MessagingException (javax.mail.MessagingException)115 Message (javax.mail.Message)81 MimeMultipart (javax.mail.internet.MimeMultipart)77 Test (org.junit.Test)77 MimeBodyPart (javax.mail.internet.MimeBodyPart)68 Date (java.util.Date)58 Transport (javax.mail.Transport)55 PasswordAuthentication (javax.mail.PasswordAuthentication)50 Multipart (javax.mail.Multipart)44 Authenticator (javax.mail.Authenticator)41 DataHandler (javax.activation.DataHandler)39 IOException (java.io.IOException)38 BodyPart (javax.mail.BodyPart)28 SMTPMessage (com.sun.mail.smtp.SMTPMessage)25 Store (javax.mail.Store)25 ByteArrayOutputStream (java.io.ByteArrayOutputStream)23