Search in sources :

Example 41 with Session

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

the class MailSubsystem20TestCase 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 42 with Session

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

the class MailSubsystem20TestCase 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"));
    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) AbstractSubsystemBaseTest(org.jboss.as.subsystem.test.AbstractSubsystemBaseTest) Test(org.junit.Test)

Example 43 with Session

use of javax.mail.Session in project SpringStepByStep by JavaProgrammerLB.

the class SendEmail method main.

public static void main(String[] args) {
    // Recipient's email ID needs to be mentioned.
    String to = "destinationemail@gmail.com";
    // Sender's email ID needs to be mentioned
    String from = "fromemail@gmail.com";
    //change accordingly
    final String username = "manishaspatil";
    //change accordingly
    final String password = "******";
    // Assuming you are sending email through relay.jangosmtp.net
    String host = "relay.jangosmtp.net";
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", "25");
    // Get the Session object.
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {

        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });
    try {
        // Create a default MimeMessage object.
        Message message = new MimeMessage(session);
        // Set From: header field of the header.
        message.setFrom(new InternetAddress(from));
        // Set To: header field of the header.
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        // Set Subject: header field
        message.setSubject("Testing Subject");
        // Now set the actual message
        message.setText("Hello, this is sample for to check send " + "email using JavaMailAPI ");
        // Send message
        Transport.send(message);
        System.out.println("Sent message successfully....");
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) Properties(java.util.Properties) Session(javax.mail.Session) PasswordAuthentication(javax.mail.PasswordAuthentication)

Example 44 with Session

use of javax.mail.Session in project SpringStepByStep by JavaProgrammerLB.

the class SendHTMLEmail method main.

public static void main(String[] args) {
    // Recipient's email ID needs to be mentioned.
    String to = "destinationemail@gmail.com";
    // Sender's email ID needs to be mentioned
    String from = "fromemail@gmail.com";
    //change accordingly
    final String username = "manishaspatil";
    //change accordingly
    final String password = "******";
    // Assuming you are sending email through relay.jangosmtp.net
    String host = "relay.jangosmtp.net";
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", "25");
    // Get the Session object.
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {

        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });
    try {
        // Create a default MimeMessage object.
        Message message = new MimeMessage(session);
        // Set From: header field of the header.
        message.setFrom(new InternetAddress(from));
        // Set To: header field of the header.
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        // Set Subject: header field
        message.setSubject("Testing Subject");
        // Send the actual HTML message, as big as you like
        message.setContent("<h1>This is actual message embedded in HTML tags</h1>", "text/html;charset=utf-8");
        // Send message
        Transport.send(message);
        System.out.println("Sent message successfully....");
    } catch (MessagingException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) Properties(java.util.Properties) Session(javax.mail.Session) PasswordAuthentication(javax.mail.PasswordAuthentication)

Example 45 with Session

use of javax.mail.Session in project SpringStepByStep by JavaProgrammerLB.

the class SendHTMLEmailWithTemplate method main.

public static void main(String[] args) throws Exception {
    Properties props = new Properties();
    try {
        props.load(new FileInputStream(new File("settings.properties")));
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    Session session = Session.getDefaultInstance(props, new Authenticator() {

        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("username", "******");
        }
    });
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("from@gmail.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to@gmail.com"));
        message.setSubject("Testing Subject");
        BodyPart body = new MimeBodyPart();
        // freemarker stuff.
        Configuration cfg = new Configuration();
        Template template = cfg.getTemplate("html-mail-template.ftl");
        Map<String, String> rootMap = new HashMap<String, String>();
        rootMap.put("to", "liubei");
        rootMap.put("body", "Sample html email using freemarker");
        rootMap.put("from", "liubei");
        Writer out = new StringWriter();
        template.process(rootMap, out);
        // freemarker stuff ends.
        /* you can add html tags in your text to decorate it. */
        body.setContent(out.toString(), "text/html");
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(body);
        body = new MimeBodyPart();
        String filename = "hello.txt";
        DataSource source = new FileDataSource(filename);
        body.setDataHandler(new DataHandler(source));
        body.setFileName(filename);
        multipart.addBodyPart(body);
        message.setContent(multipart, "text/html;charset=utf-8");
        Transport.send(message);
    } catch (MessagingException e) {
        e.printStackTrace();
    }
    System.out.println("Done....");
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) InternetAddress(javax.mail.internet.InternetAddress) Multipart(javax.mail.Multipart) MimeMultipart(javax.mail.internet.MimeMultipart) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) Configuration(freemarker.template.Configuration) HashMap(java.util.HashMap) FileNotFoundException(java.io.FileNotFoundException) DataHandler(javax.activation.DataHandler) Properties(java.util.Properties) Template(freemarker.template.Template) StringWriter(java.io.StringWriter) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) FileDataSource(javax.activation.FileDataSource) Authenticator(javax.mail.Authenticator) PasswordAuthentication(javax.mail.PasswordAuthentication) MessagingException(javax.mail.MessagingException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) FileDataSource(javax.activation.FileDataSource) DataSource(javax.activation.DataSource) MimeBodyPart(javax.mail.internet.MimeBodyPart) File(java.io.File) StringWriter(java.io.StringWriter) Writer(java.io.Writer) 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