Search in sources :

Example 76 with Session

use of javax.mail.Session in project wildfly by wildfly.

the class StatelessMailBean method testMail.

public void testMail() throws NamingException {
    Context initCtx = new InitialContext();
    Context myEnv = (Context) initCtx.lookup("java:comp/env");
    // JavaMail Session
    Object obj = myEnv.lookup("MyDefaultMail");
    if ((obj instanceof javax.mail.Session) == false) {
        throw new NamingException("DefaultMail is not a javax.mail.Session");
    }
}
Also used : InitialContext(javax.naming.InitialContext) Context(javax.naming.Context) NamingException(javax.naming.NamingException) InitialContext(javax.naming.InitialContext) Session(javax.mail.Session)

Example 77 with Session

use of javax.mail.Session in project wildfly by wildfly.

the class MailSubsystem21TestCase method testOperations.

@Test
public void testOperations() throws Exception {
    KernelServicesBuilder builder = createKernelServicesBuilder(new MailSubsystem10TestCase.Initializer()).setSubsystemXml(getSubsystemXml());
    KernelServices mainServices = builder.build();
    if (!mainServices.isSuccessfulBoot()) {
        Assert.fail(mainServices.getBootError().toString());
    }
    PathAddress sessionAddress = PathAddress.pathAddress(MailExtension.SUBSYSTEM_PATH, PathElement.pathElement(MailExtension.MAIL_SESSION_PATH.getKey(), "defaultMail"));
    ModelNode result;
    ModelNode removeServerOp = Util.createRemoveOperation(sessionAddress.append("server", "imap"));
    removeServerOp.get(OPERATION_HEADERS).get(ALLOW_RESOURCE_SERVICE_RESTART).set(true);
    result = mainServices.executeOperation(removeServerOp);
    checkResult(result);
    ModelNode addServerOp = Util.createAddOperation(sessionAddress.append("server", "imap"));
    addServerOp.get(OPERATION_HEADERS).get(ALLOW_RESOURCE_SERVICE_RESTART).set(true);
    addServerOp.get("outbound-socket-binding-ref").set("mail-imap");
    addServerOp.get("username").set("user");
    addServerOp.get("password").set("pswd");
    result = mainServices.executeOperation(addServerOp);
    checkResult(result);
    //to make sure noting is left behind
    checkResult(mainServices.executeOperation(removeServerOp));
    checkResult(mainServices.executeOperation(addServerOp));
    ModelNode writeOp = Util.createEmptyOperation(WRITE_ATTRIBUTE_OPERATION, sessionAddress);
    writeOp.get(OPERATION_HEADERS).get(ALLOW_RESOURCE_SERVICE_RESTART).set(true);
    writeOp.get("name").set("debug");
    writeOp.get("value").set(false);
    result = mainServices.executeOperation(writeOp);
    checkResult(result);
    ServiceController<?> javaMailService = mainServices.getContainer().getService(MailSessionAdd.MAIL_SESSION_SERVICE_NAME.append("defaultMail"));
    javaMailService.setMode(ServiceController.Mode.ACTIVE);
    Session session = (Session) javaMailService.getValue();
    Assert.assertNotNull("session should not be null", session);
    Properties properties = session.getProperties();
    Assert.assertNotNull("smtp host should be set", properties.getProperty("mail.smtp.host"));
    Assert.assertNotNull("imap host should be set", properties.getProperty("mail.imap.host"));
    PathAddress nonExisting = PathAddress.pathAddress(MailExtension.SUBSYSTEM_PATH, PathElement.pathElement(MailExtension.MAIL_SESSION_PATH.getKey(), "non-existing-session"));
    ModelNode addSession = Util.createAddOperation(nonExisting);
    addSession.get("jndi-name").set("java:/bah");
    checkResult(mainServices.executeOperation(addSession));
    removeServerOp = Util.createRemoveOperation(nonExisting.append("server", "imap"));
    //removeServerOp.get(OPERATION_HEADERS).get(ALLOW_RESOURCE_SERVICE_RESTART).set(true);
    result = mainServices.executeOperation(removeServerOp);
    checkForFailure(result);
}
Also used : PathAddress(org.jboss.as.controller.PathAddress) KernelServices(org.jboss.as.subsystem.test.KernelServices) ModelNode(org.jboss.dmr.ModelNode) Properties(java.util.Properties) KernelServicesBuilder(org.jboss.as.subsystem.test.KernelServicesBuilder) Session(javax.mail.Session) AbstractSubsystemBaseTest(org.jboss.as.subsystem.test.AbstractSubsystemBaseTest) Test(org.junit.Test)

Example 78 with Session

use of javax.mail.Session in project wildfly by wildfly.

the class MailSubsystem21TestCase method testRuntime.

@Test
public void testRuntime() throws Exception {
    KernelServicesBuilder builder = createKernelServicesBuilder(new MailSubsystem10TestCase.Initializer()).setSubsystemXml(getSubsystemXml());
    KernelServices mainServices = builder.build();
    if (!mainServices.isSuccessfulBoot()) {
        Assert.fail(mainServices.getBootError().toString());
    }
    ServiceController<?> javaMailService = mainServices.getContainer().getService(MailSessionAdd.MAIL_SESSION_SERVICE_NAME.append("defaultMail"));
    javaMailService.setMode(ServiceController.Mode.ACTIVE);
    Session session = (Session) javaMailService.getValue();
    Assert.assertNotNull("session should not be null", session);
    Properties properties = session.getProperties();
    Assert.assertNotNull("smtp host should be set", properties.getProperty("mail.smtp.host"));
    Assert.assertNotNull("pop3 host should be set", properties.getProperty("mail.pop3.host"));
    Assert.assertNotNull("imap host should be set", properties.getProperty("mail.imap.host"));
    PasswordAuthentication auth = session.requestPasswordAuthentication(InetAddress.getLocalHost(), 25, "smtp", "", "");
    Assert.assertEquals("nobody", auth.getUserName());
    Assert.assertEquals("pass", auth.getPassword());
    ServiceController<?> defaultMailService = mainServices.getContainer().getService(MailSessionAdd.MAIL_SESSION_SERVICE_NAME.append("default2"));
    session = (Session) defaultMailService.getValue();
    Assert.assertEquals("Debug should be true", true, session.getDebug());
    ServiceController<?> customMailService = mainServices.getContainer().getService(MailSessionAdd.MAIL_SESSION_SERVICE_NAME.append("custom"));
    session = (Session) customMailService.getValue();
    properties = session.getProperties();
    String host = properties.getProperty("mail.smtp.host");
    Assert.assertNotNull("smtp host should be set", host);
    Assert.assertEquals("mail.example.com", host);
    //this one should be read out of socket binding
    Assert.assertEquals("localhost", properties.get("mail.pop3.host"));
    //this one should be extra property
    Assert.assertEquals("some-custom-prop-value", properties.get("mail.pop3.custom_prop"));
    //this one should be extra property
    Assert.assertEquals("fully-qualified-prop-name", properties.get("some.fully.qualified.property"));
    MailSessionService service = (MailSessionService) customMailService.getService();
    Credentials credentials = service.getConfig().getCustomServers()[0].getCredentials();
    Assert.assertEquals(credentials.getUsername(), "username");
    Assert.assertEquals(credentials.getPassword(), "password");
}
Also used : KernelServices(org.jboss.as.subsystem.test.KernelServices) Properties(java.util.Properties) KernelServicesBuilder(org.jboss.as.subsystem.test.KernelServicesBuilder) Session(javax.mail.Session) PasswordAuthentication(javax.mail.PasswordAuthentication) AbstractSubsystemBaseTest(org.jboss.as.subsystem.test.AbstractSubsystemBaseTest) Test(org.junit.Test)

Example 79 with Session

use of javax.mail.Session in project nhin-d by DirectProject.

the class XDMMailClient method sendMail.

/**
     * Create and send a message over SMTP.
     * 
     * @param recipients
     *            The list of recipient addresses for the mail message.
     * @param subject
     *            The subject of the mail message.
     * @param messageId
     *            The message ID.
     * @param body
     *            The body body of the message.
     * @param message
     *            The data to be zipped and attached to the mail message.
     * @param from
     *            The sender of the mail message.
     * @param suffix
     *            The suffix of the data to be zipped and attached to the mail
     *            message.
     * @param meta
     *            The metadata to be included in the zip and attached to the
     *            mail message.
     * @throws MessagingException
     */
public void sendMail(String messageId, String from, List<String> recipients, String body, DirectDocuments documents, String suffix) throws MessagingException {
    boolean debug = false;
    java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
    String subject = "data";
    // Set the host SMTP address
    Properties props = new Properties();
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", smtpHostName);
    props.put("mail.smtp.auth", "true");
    Authenticator auth = new SMTPAuthenticator();
    Session session = Session.getInstance(props, auth);
    session.setDebug(debug);
    InternetAddress addressFrom = new InternetAddress(from);
    InternetAddress[] addressTo = new InternetAddress[recipients.size()];
    int i = 0;
    for (String recipient : recipients) {
        addressTo[i++] = new InternetAddress(recipient);
    }
    // Build message object
    mmessage = new MimeMessage(session);
    mmessage.setFrom(addressFrom);
    mmessage.setRecipients(Message.RecipientType.TO, addressTo);
    mmessage.setSubject(subject);
    mailBody = new MimeMultipart();
    mainBody = new MimeBodyPart();
    mainBody.setDataHandler(new DataHandler(body, "text/plain"));
    mailBody.addBodyPart(mainBody);
    try {
        mimeAttach = new MimeBodyPart();
        mimeAttach.attachFile(documents.toXdmPackage(messageId).toFile());
    } catch (IOException e) {
        throw new MessagingException("Unable to create/attach xdm file", e);
    }
    mailBody.addBodyPart(mimeAttach);
    mmessage.setContent(mailBody);
    Transport.send(mmessage);
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) MessagingException(javax.mail.MessagingException) DataHandler(javax.activation.DataHandler) IOException(java.io.IOException) Properties(java.util.Properties) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) MimeBodyPart(javax.mail.internet.MimeBodyPart) Authenticator(javax.mail.Authenticator) Session(javax.mail.Session)

Example 80 with Session

use of javax.mail.Session in project nhin-d by DirectProject.

the class MessageServiceImplService method sendMessage.

@Override
public /**
     * Converts an incoming WS request into an email message and sends it to the configured 
     * email server
     */
SendResponseType sendMessage(EmailType body) {
    if (log.isDebugEnabled())
        log.debug("Enter");
    SendResponseType response = new SendResponseType();
    checkAuth(response);
    if (response.getError() == null) {
        log.info("Auth success");
        Multipart mailBody;
        MimeBodyPart mainBody;
        MimeBodyPart mimeAttach;
        String fromaddress = body.getHead().getFrom().getAddress();
        log.info("Got FROM address");
        try {
            InternetAddress addressFrom;
            addressFrom = new InternetAddress(fromaddress.toString());
            if (log.isDebugEnabled())
                log.debug("Sender: " + addressFrom);
            InternetAddress[] addressTo = new InternetAddress[1];
            int i = 0;
            for (AddressType recipient : body.getHead().getTo()) {
                addressTo[i] = new InternetAddress(recipient.getAddress());
                if (log.isDebugEnabled())
                    log.debug("Recipient: " + addressTo[i]);
                i++;
            }
            Session session = Session.getInstance(smtpProps, new SMTPAuthenticator());
            // Build message object
            MimeMessage mimeMsg = new MimeMessage(session);
            mimeMsg.setFrom(addressFrom);
            mimeMsg.setRecipients(Message.RecipientType.TO, addressTo);
            if (body.getHead().getSubject() != null) {
                mimeMsg.setSubject(body.getHead().getSubject());
            } else {
                mimeMsg.setSubject("Direct message");
            }
            mailBody = new MimeMultipart();
            mainBody = new MimeBodyPart();
            if (body.getBody().getText() != null) {
                mainBody.setText(body.getBody().getText());
            } else {
                mainBody.setText("");
            }
            mailBody.addBodyPart(mainBody);
            copyAttachments(body, mailBody);
            mimeMsg.setContent(mailBody);
            DirectMimeMessage dMsg = new DirectMimeMessage(mimeMsg, getSenderHost());
            dMsg.updateMessageID();
            Transport transport;
            if (getUseTLSforSMTP().equals("SOCKET")) {
                transport = session.getTransport("smtps");
            } else {
                transport = session.getTransport("smtp");
            }
            transport.connect();
            try {
                transport.sendMessage(dMsg, addressTo);
                // Transport.send(dMsg);
                response.setMessageID(dMsg.getMessageID());
                transport.close();
            } finally {
                transport.close();
            }
        } catch (AddressException e) {
            ErrorType et = new ErrorType();
            et.setCode(ErrorCodeType.ADDRESSING);
            et.setMessage(e.getMessage());
            response.setError(et);
            log.error(e);
        } catch (MessagingException e) {
            ErrorType et = new ErrorType();
            et.setCode(ErrorCodeType.MESSAGING);
            et.setMessage(e.getMessage());
            response.setError(et);
            log.error(e);
        } catch (Exception e) {
            ErrorType et = new ErrorType();
            et.setCode(ErrorCodeType.SYSTEM);
            et.setMessage(e.getMessage());
            response.setError(et);
            log.error(e);
            e.printStackTrace();
        }
    }
    return response;
}
Also used : Multipart(javax.mail.Multipart) MimeMultipart(javax.mail.internet.MimeMultipart) InternetAddress(javax.mail.internet.InternetAddress) MessagingException(javax.mail.MessagingException) SendResponseType(org.nhindirect.schema.edge.ws.SendResponseType) MessagingException(javax.mail.MessagingException) AddressException(javax.mail.internet.AddressException) InvalidPropertyException(org.springframework.beans.InvalidPropertyException) IOException(java.io.IOException) ErrorType(org.nhindirect.schema.edge.ws.ErrorType) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) AddressException(javax.mail.internet.AddressException) MimeBodyPart(javax.mail.internet.MimeBodyPart) AddressType(org.nhindirect.schema.edge.ws.AddressType) Transport(javax.mail.Transport) Session(javax.mail.Session)

Aggregations

Session (javax.mail.Session)110 MimeMessage (javax.mail.internet.MimeMessage)72 Properties (java.util.Properties)66 InternetAddress (javax.mail.internet.InternetAddress)49 MessagingException (javax.mail.MessagingException)47 Message (javax.mail.Message)31 Test (org.junit.Test)30 Transport (javax.mail.Transport)28 JMSession (com.zimbra.cs.util.JMSession)20 PasswordAuthentication (javax.mail.PasswordAuthentication)19 Date (java.util.Date)17 MimeBodyPart (javax.mail.internet.MimeBodyPart)16 MimeMultipart (javax.mail.internet.MimeMultipart)16 ZMimeMessage (com.zimbra.common.zmime.ZMimeMessage)15 IOException (java.io.IOException)15 SharedByteArrayInputStream (javax.mail.util.SharedByteArrayInputStream)15 Authenticator (javax.mail.Authenticator)12 Multipart (javax.mail.Multipart)11 NoSuchProviderException (javax.mail.NoSuchProviderException)10 BodyPart (javax.mail.BodyPart)9