Search in sources :

Example 56 with Message

use of javax.mail.Message 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 57 with Message

use of javax.mail.Message 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)

Example 58 with Message

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

the class SendAttachmentInEmail 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");
        // Create the message part
        BodyPart messageBodyPart = new MimeBodyPart();
        // Now set the actual message
        messageBodyPart.setText("This is message body");
        // Create a multipar message
        Multipart multipart = new MimeMultipart();
        // Set text message part
        multipart.addBodyPart(messageBodyPart);
        // Part two is attachment
        messageBodyPart = new MimeBodyPart();
        String filename = "/home/manisha/file.txt";
        DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(filename);
        multipart.addBodyPart(messageBodyPart);
        // Send the complete message parts
        message.setContent(multipart);
        // Send message
        Transport.send(message);
        System.out.println("Sent message successfully....");
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) InternetAddress(javax.mail.internet.InternetAddress) MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) DataHandler(javax.activation.DataHandler) Properties(java.util.Properties) FileDataSource(javax.activation.FileDataSource) DataSource(javax.activation.DataSource) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) FileDataSource(javax.activation.FileDataSource) MimeBodyPart(javax.mail.internet.MimeBodyPart) Session(javax.mail.Session) PasswordAuthentication(javax.mail.PasswordAuthentication)

Example 59 with Message

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

the class AccountEmailServiceTest method testSendMail.

@Test
public void testSendMail() throws Exception {
    ApplicationContext ctx = new ClassPathXmlApplicationContext("account-email.xml");
    AccountEmailService accountEmailService = (AccountEmailService) ctx.getBean("accountEmailService");
    String subject = "Test Subject";
    String htmlText = "<h3>Test</h3>";
    accountEmailService.sendMail("test2@juvenxu.com", subject, htmlText);
    greenMail.waitForIncomingEmail(2000, 1);
    Message[] msgs = greenMail.getReceivedMessages();
    assertEquals(1, msgs.length);
    assertEquals(subject, msgs[0].getSubject());
    assertEquals(htmlText, GreenMailUtil.getBody(msgs[0]).trim());
}
Also used : ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) ApplicationContext(org.springframework.context.ApplicationContext) Message(javax.mail.Message) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) Test(org.junit.Test)

Example 60 with Message

use of javax.mail.Message in project jmeter by apache.

the class MailReaderSampler method sample.

/**
     * {@inheritDoc}
     */
@Override
public SampleResult sample(Entry e) {
    SampleResult parent = new SampleResult();
    // Did sample succeed?
    boolean isOK = false;
    final boolean deleteMessages = getDeleteMessages();
    final String serverProtocol = getServerType();
    parent.setSampleLabel(getName());
    String samplerString = toString();
    parent.setSamplerData(samplerString);
    /*
         * Perform the sampling
         */
    // Start timing
    parent.sampleStart();
    try {
        // Create empty properties
        Properties props = new Properties();
        if (isUseStartTLS()) {
            // $NON-NLS-1$
            props.setProperty(mailProp(serverProtocol, "starttls.enable"), TRUE);
            if (isEnforceStartTLS()) {
                // Requires JavaMail 1.4.2+
                // $NON-NLS-1$
                props.setProperty(mailProp(serverProtocol, "starttls.require"), TRUE);
            }
        }
        if (isTrustAllCerts()) {
            if (isUseSSL()) {
                // $NON-NLS-1$
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.class"), TRUST_ALL_SOCKET_FACTORY);
                // $NON-NLS-1$
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE);
            } else if (isUseStartTLS()) {
                // $NON-NLS-1$
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.class"), TRUST_ALL_SOCKET_FACTORY);
                // $NON-NLS-1$
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE);
            }
        } else if (isUseLocalTrustStore()) {
            File truststore = new File(getTrustStoreToUse());
            log.info("load local truststore - try to load truststore from: " + truststore.getAbsolutePath());
            if (!truststore.exists()) {
                log.info("load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath());
                truststore = new File(FileServer.getFileServer().getBaseDir(), getTrustStoreToUse());
                log.info("load local truststore -Attempting to read truststore from:  " + truststore.getAbsolutePath());
                if (!truststore.exists()) {
                    log.info("load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath() + ". Local truststore not available, aborting execution.");
                    throw new IOException("Local truststore file not found. Also not available under : " + truststore.getAbsolutePath());
                }
            }
            if (isUseSSL()) {
                // Requires JavaMail 1.4.2+
                // $NON-NLS-1$ 
                props.put(// $NON-NLS-1$ 
                mailProp(serverProtocol, "ssl.socketFactory"), new LocalTrustStoreSSLSocketFactory(truststore));
                // $NON-NLS-1$
                props.put(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE);
            } else if (isUseStartTLS()) {
                // Requires JavaMail 1.4.2+
                // $NON-NLS-1$
                props.put(// $NON-NLS-1$
                mailProp(serverProtocol, "ssl.socketFactory"), new LocalTrustStoreSSLSocketFactory(truststore));
                // $NON-NLS-1$
                props.put(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE);
            }
        }
        // Get session
        Session session = Session.getInstance(props, null);
        // Get the store
        Store store = session.getStore(serverProtocol);
        store.connect(getServer(), getPortAsInt(), getUserName(), getPassword());
        // Get folder
        Folder folder = store.getFolder(getFolder());
        if (deleteMessages) {
            folder.open(Folder.READ_WRITE);
        } else {
            folder.open(Folder.READ_ONLY);
        }
        final int messageTotal = folder.getMessageCount();
        int n = getNumMessages();
        if (n == ALL_MESSAGES || n > messageTotal) {
            n = messageTotal;
        }
        // Get directory
        Message[] messages = folder.getMessages(1, n);
        StringBuilder pdata = new StringBuilder();
        pdata.append(messages.length);
        pdata.append(" messages found\n");
        parent.setResponseData(pdata.toString(), null);
        parent.setDataType(SampleResult.TEXT);
        // $NON-NLS-1$
        parent.setContentType("text/plain");
        final boolean headerOnly = getHeaderOnly();
        busy = true;
        for (Message message : messages) {
            StringBuilder cdata = new StringBuilder();
            SampleResult child = new SampleResult();
            child.sampleStart();
            // $NON-NLS-1$
            cdata.append("Message ");
            cdata.append(message.getMessageNumber());
            child.setSampleLabel(cdata.toString());
            child.setSamplerData(cdata.toString());
            cdata.setLength(0);
            final String contentType = message.getContentType();
            // Store the content-type
            child.setContentType(contentType);
            // RFC 822 uses ascii per default
            child.setDataEncoding(RFC_822_DEFAULT_ENCODING);
            // Parse the content-type
            child.setEncodingAndType(contentType);
            if (isStoreMimeMessage()) {
                // Don't save headers - they are already in the raw message
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                message.writeTo(bout);
                // Save raw message
                child.setResponseData(bout.toByteArray());
                child.setDataType(SampleResult.TEXT);
            } else {
                // Javadoc for the API says this is OK
                @SuppressWarnings("unchecked") Enumeration<Header> hdrs = message.getAllHeaders();
                while (hdrs.hasMoreElements()) {
                    Header hdr = hdrs.nextElement();
                    String value = hdr.getValue();
                    try {
                        value = MimeUtility.decodeText(value);
                    } catch (UnsupportedEncodingException uce) {
                    // ignored
                    }
                    cdata.append(hdr.getName()).append(": ").append(value).append("\n");
                }
                child.setResponseHeaders(cdata.toString());
                cdata.setLength(0);
                if (!headerOnly) {
                    appendMessageData(child, message);
                }
            }
            if (deleteMessages) {
                message.setFlag(Flags.Flag.DELETED, true);
            }
            child.setResponseOK();
            if (child.getEndTime() == 0) {
                // Avoid double-call if addSubResult was called.
                child.sampleEnd();
            }
            parent.addSubResult(child);
        }
        // Close connection
        folder.close(true);
        store.close();
        parent.setResponseCodeOK();
        parent.setResponseMessageOK();
        isOK = true;
    } catch (NoClassDefFoundError | IOException ex) {
        // No need to log normally, as we set the status
        log.debug("", ex);
        // $NON-NLS-1$
        parent.setResponseCode("500");
        parent.setResponseMessage(ex.toString());
    } catch (MessagingException ex) {
        // No need to log normally, as we set the status
        log.debug("", ex);
        // $NON-NLS-1$
        parent.setResponseCode("500");
        // $NON-NLS-1$
        parent.setResponseMessage(ex.toString() + "\n" + samplerString);
    } finally {
        busy = false;
    }
    if (parent.getEndTime() == 0) {
        // not been set by any child samples
        parent.sampleEnd();
    }
    parent.setSuccessful(isOK);
    return parent;
}
Also used : Message(javax.mail.Message) MessagingException(javax.mail.MessagingException) Store(javax.mail.Store) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Properties(java.util.Properties) Folder(javax.mail.Folder) LocalTrustStoreSSLSocketFactory(org.apache.jmeter.protocol.smtp.sampler.protocol.LocalTrustStoreSSLSocketFactory) Header(javax.mail.Header) SampleResult(org.apache.jmeter.samplers.SampleResult) File(java.io.File) Session(javax.mail.Session)

Aggregations

Message (javax.mail.Message)149 MimeMessage (javax.mail.internet.MimeMessage)81 MessagingException (javax.mail.MessagingException)53 InternetAddress (javax.mail.internet.InternetAddress)48 Folder (javax.mail.Folder)41 Test (org.junit.Test)40 Session (javax.mail.Session)37 Properties (java.util.Properties)36 Store (javax.mail.Store)28 Date (java.util.Date)19 MockEndpoint (org.apache.camel.component.mock.MockEndpoint)19 MimeMultipart (javax.mail.internet.MimeMultipart)18 Mailbox (org.jvnet.mock_javamail.Mailbox)18 MimeBodyPart (javax.mail.internet.MimeBodyPart)16 PasswordAuthentication (javax.mail.PasswordAuthentication)15 IOException (java.io.IOException)13 ArrayList (java.util.ArrayList)13 Multipart (javax.mail.Multipart)13 Address (javax.mail.Address)11 HashMap (java.util.HashMap)8