List of usage examples for javax.mail Session getProperties
public Properties getProperties()
From source file:com.zxy.commons.email.MailMessageUtils.java
/** * HtmlEmail/* w ww .j a v a 2 s . c o m*/ * * @return HtmlEmail */ @SuppressWarnings("PMD.EmptyCatchBlock") private static HtmlEmail getEmail() { HtmlEmail email = new HtmlEmail(); email.setHostName(SMTP_HOST); email.setSmtpPort(SMTP_PORT); if (StringUtils.isNotBlank(SMTP_USERNAME) && StringUtils.isNotBlank(SMTP_PASSWORD)) { email.setAuthentication(SMTP_USERNAME, SMTP_PASSWORD); } try { Session session = email.getMailSession(); session.getProperties().setProperty("mail.smtp.ehlo", "true"); } catch (EmailException e) { // do nothing } if (StringUtils.isNotBlank(SMTP_MAIL_CHARSET)) { email.setCharset(SMTP_MAIL_CHARSET); } return email; }
From source file:com.zimbra.cs.mailclient.smtp.SmtpTransportTest.java
@Test(timeout = 3000) public void mailSmtpFrom() throws Exception { server = MockTcpServer.scenario().sendLine("220 test ready").recvLine() // EHLO .sendLine("250 OK").recvLine() // MAIL FROM .sendLine("250 OK").recvLine() // RCPT TO .sendLine("250 OK").recvLine() // DATA .sendLine("354 OK").swallowUntil("\r\n.\r\n").sendLine("250 OK").recvLine() // QUIT .sendLine("221 bye").build().start(PORT); Session session = JMSession.getSession(); session.getProperties().setProperty("mail.smtp.from", "from@zimbra.com"); Transport transport = session.getTransport("smtp"); transport.connect("localhost", PORT, null, null); String raw = "From: sender@zimbra.com\nTo: rcpt@zimbra.com\nSubject: test\n\ntest"; MimeMessage msg = new ZMimeMessage(session, new SharedByteArrayInputStream(raw.getBytes(Charsets.ISO_8859_1))); transport.sendMessage(msg, msg.getAllRecipients()); transport.close();//from w w w . j ava2 s . co m server.shutdown(1000); Assert.assertEquals("EHLO localhost\r\n", server.replay()); Assert.assertEquals("MAIL FROM:<from@zimbra.com>\r\n", server.replay()); Assert.assertEquals("RCPT TO:<rcpt@zimbra.com>\r\n", server.replay()); Assert.assertEquals("DATA\r\n", server.replay()); Assert.assertEquals("QUIT\r\n", server.replay()); Assert.assertNull(server.replay()); }
From source file:com.zimbra.cs.mailclient.smtp.SmtpTransportTest.java
@Test(timeout = 3000) public void bracketsInMailAndRcpt() throws Exception { server = MockTcpServer.scenario().sendLine("220 test ready").recvLine() // EHLO .sendLine("250 OK").recvLine() // MAIL FROM .sendLine("250 OK").recvLine() // RCPT TO .sendLine("250 OK").recvLine() // DATA .sendLine("354 OK").swallowUntil("\r\n.\r\n").sendLine("250 OK").recvLine() // QUIT .sendLine("221 bye").build().start(PORT); Session session = JMSession.getSession(); session.getProperties().setProperty("mail.smtp.from", "<>"); Transport transport = session.getTransport("smtp"); transport.connect("localhost", PORT, null, null); String raw = "From: sender@zimbra.com\nTo: rcpt@zimbra.com\nSubject: test\n\ntest"; MimeMessage msg = new ZMimeMessage(session, new SharedByteArrayInputStream(raw.getBytes(Charsets.ISO_8859_1))); transport.sendMessage(msg, new Address[] { new InternetAddress("<rcpt@zimbra.com>") }); transport.close();// w w w . j a v a 2 s. c o m server.shutdown(1000); Assert.assertEquals("EHLO localhost\r\n", server.replay()); Assert.assertEquals("MAIL FROM:<>\r\n", server.replay()); Assert.assertEquals("RCPT TO:<rcpt@zimbra.com>\r\n", server.replay()); Assert.assertEquals("DATA\r\n", server.replay()); Assert.assertEquals("QUIT\r\n", server.replay()); Assert.assertNull(server.replay()); }
From source file:com.zimbra.cs.mailclient.smtp.SmtpTransportTest.java
@Test(timeout = 3000) public void nullMailFrom() throws Exception { server = MockTcpServer.scenario().sendLine("220 test ready").recvLine() // EHLO .sendLine("250 OK").recvLine() // MAIL FROM .sendLine("250 OK").recvLine() // RCPT TO .sendLine("250 OK").recvLine() // DATA .sendLine("354 OK").swallowUntil("\r\n.\r\n").sendLine("250 OK").recvLine() // QUIT .sendLine("221 bye").build().start(PORT); Session session = JMSession.getSession(); session.getProperties().setProperty("mail.smtp.from", "from@zimbra.com"); Transport transport = session.getTransport("smtp"); transport.connect("localhost", PORT, null, null); String raw = "From: sender@zimbra.com\nTo: rcpt@zimbra.com\nSubject: test\n\ntest"; SMTPMessage msg = new SMTPMessage(session, new SharedByteArrayInputStream(raw.getBytes(Charsets.ISO_8859_1))); msg.setEnvelopeFrom("<>"); // this should override the previously set mail.smtp.from transport.sendMessage(msg, msg.getAllRecipients()); transport.close();//from ww w . j a v a 2 s .co m server.shutdown(1000); Assert.assertEquals("EHLO localhost\r\n", server.replay()); Assert.assertEquals("MAIL FROM:<>\r\n", server.replay()); Assert.assertEquals("RCPT TO:<rcpt@zimbra.com>\r\n", server.replay()); Assert.assertEquals("DATA\r\n", server.replay()); Assert.assertEquals("QUIT\r\n", server.replay()); Assert.assertNull(server.replay()); }
From source file:com.zimbra.cs.mailclient.smtp.SmtpTransportTest.java
@Test(timeout = 3000) public void rcptToError() throws Exception { server = MockTcpServer.scenario().sendLine("220 test ready").recvLine() // EHLO .sendLine("250 OK").recvLine() // MAIL FROM .sendLine("250 OK").recvLine() // RCPT TO .sendLine("550 error").recvLine() // QUIT .build().start(PORT);/*from ww w . j a v a 2 s . co m*/ Session session = JMSession.getSession(); session.getProperties().setProperty("mail.smtp.sendpartial", "true"); Transport transport = session.getTransport("smtp"); transport.connect("localhost", PORT, null, null); String raw = "From: sender@zimbra.com\nTo: rcpt@zimbra.com\nSubject: test\n\ntest"; MimeMessage msg = new ZMimeMessage(session, new SharedByteArrayInputStream(raw.getBytes(Charsets.ISO_8859_1))); try { transport.sendMessage(msg, msg.getAllRecipients()); Assert.fail(); } catch (SendFailedException e) { Assert.assertEquals(0, e.getValidSentAddresses().length); Assert.assertEquals(0, e.getValidUnsentAddresses().length); Assert.assertEquals(1, e.getInvalidAddresses().length); } finally { transport.close(); } server.shutdown(1000); Assert.assertEquals("EHLO localhost\r\n", server.replay()); Assert.assertEquals("MAIL FROM:<sender@zimbra.com>\r\n", server.replay()); Assert.assertEquals("RCPT TO:<rcpt@zimbra.com>\r\n", server.replay()); Assert.assertEquals("QUIT\r\n", server.replay()); Assert.assertNull(server.replay()); }
From source file:com.zimbra.cs.mailclient.smtp.SmtpTransportTest.java
@Test(timeout = 3000) public void sendPartially() throws Exception { server = MockTcpServer.scenario().sendLine("220 test ready").recvLine() // EHLO .sendLine("250 OK").recvLine() // MAIL FROM .sendLine("250 OK").recvLine() // RCPT TO 1 .sendLine("250 OK").recvLine() // RCPT TO 2 .sendLine("550 not found").recvLine() // RCPT TO 3 .sendLine("550 not found").recvLine() // DATA .sendLine("354 OK").swallowUntil("\r\n.\r\n").sendLine("250 OK").recvLine() // QUIT .sendLine("221 bye").build().start(PORT); Session session = JMSession.getSession(); session.getProperties().setProperty("mail.smtp.sendpartial", "true"); Transport transport = session.getTransport("smtp"); transport.connect("localhost", PORT, null, null); String raw = "From: sender@zimbra.com\n" + "To: rcpt1@zimbra.com, rcpt2@zimbra.com, rcpt3@zimbra.com\nSubject: test\n\ntest"; MimeMessage msg = new ZMimeMessage(session, new SharedByteArrayInputStream(raw.getBytes(Charsets.ISO_8859_1))); try {// ww w .j a va 2 s . c o m transport.sendMessage(msg, msg.getAllRecipients()); } catch (SendFailedException e) { Assert.assertEquals(1, e.getValidSentAddresses().length); Assert.assertEquals(0, e.getValidUnsentAddresses().length); Assert.assertEquals(2, e.getInvalidAddresses().length); } finally { transport.close(); } server.shutdown(1000); Assert.assertEquals("EHLO localhost\r\n", server.replay()); Assert.assertEquals("MAIL FROM:<sender@zimbra.com>\r\n", server.replay()); Assert.assertEquals("RCPT TO:<rcpt1@zimbra.com>\r\n", server.replay()); Assert.assertEquals("RCPT TO:<rcpt2@zimbra.com>\r\n", server.replay()); Assert.assertEquals("RCPT TO:<rcpt3@zimbra.com>\r\n", server.replay()); Assert.assertEquals("DATA\r\n", server.replay()); Assert.assertEquals("QUIT\r\n", server.replay()); Assert.assertNull(server.replay()); }
From source file:org.fao.geonet.util.MailUtil.java
/** * Create data information to compose the mail * * @param hostName/*w w w. j a v a 2s .c o m*/ * @param smtpPort * @param from * @param username * @param password * @param email * @param ssl * @param tls * @param ignoreSslCertificateErrors */ private static void configureBasics(String hostName, Integer smtpPort, String from, String username, String password, Email email, Boolean ssl, Boolean tls, Boolean ignoreSslCertificateErrors) { if (hostName != null) { email.setHostName(hostName); } else { throw new IllegalArgumentException( "Missing settings in System Configuration (see Administration menu) - cannot send mail"); } if (StringUtils.isNotBlank(smtpPort + "")) { email.setSmtpPort(smtpPort); } else { throw new IllegalArgumentException( "Missing settings in System Configuration (see Administration menu) - cannot send mail"); } if (username != null) { email.setAuthenticator(new DefaultAuthenticator(username, password)); } email.setDebug(true); if (tls != null && tls) { email.setStartTLSEnabled(tls); email.setStartTLSRequired(tls); } if (ssl != null && ssl) { email.setSSLOnConnect(ssl); if (StringUtils.isNotBlank(smtpPort + "")) { email.setSslSmtpPort(smtpPort + ""); } } if (ignoreSslCertificateErrors != null && ignoreSslCertificateErrors) { try { Session mailSession = email.getMailSession(); Properties p = mailSession.getProperties(); p.setProperty("mail.smtp.ssl.trust", "*"); } catch (EmailException e) { // Ignore the exception. Can't be reached because the host name is always set above or an // IllegalArgumentException is thrown. } } if (StringUtils.isNotBlank(from)) { try { email.setFrom(from); } catch (EmailException e) { throw new IllegalArgumentException( "Invalid 'from' email setting in System Configuration (see Administration menu) - cannot send " + "mail", e); } } else { throw new IllegalArgumentException( "Missing settings in System Configuration (see Administration menu) - cannot send mail"); } }
From source file:org.georchestra.console.mailservice.Email.java
protected void sendMsg(String msg) throws AddressException, MessagingException { if (LOG.isDebugEnabled()) { LOG.debug("body: " + msg); }/*from w w w . ja v a 2 s .c o m*/ // Replace {publicUrl} token with the configured public URL msg = msg.replaceAll("\\{publicUrl\\}", this.georConfig.getProperty("publicUrl")); final Session session = Session.getInstance(System.getProperties(), null); session.getProperties().setProperty("mail.smtp.host", smtpHost); session.getProperties().setProperty("mail.smtp.port", (new Integer(smtpPort)).toString()); final MimeMessage message = new MimeMessage(session); if (isValidEmailAddress(from)) { message.setFrom(new InternetAddress(from)); } boolean validRecipients = false; for (String recipient : recipients) { if (isValidEmailAddress(recipient)) { validRecipients = true; message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient)); } } if (!validRecipients) { message.addRecipient(Message.RecipientType.TO, new InternetAddress(from)); message.setSubject("[ERREUR] Message non dlivr : " + subject, subjectEncoding); } else { message.setSubject(subject, subjectEncoding); } if (msg != null) { /* See http://www.rgagnon.com/javadetails/java-0321.html */ if ("true".equalsIgnoreCase(emailHtml)) { message.setContent(msg, "text/html; charset=" + bodyEncoding); } else { message.setContent(msg, "text/plain; charset=" + bodyEncoding); } LOG.debug(msg); } Transport.send(message); LOG.debug("email has been sent to:\n" + Arrays.toString(recipients)); }
From source file:org.georchestra.console.ws.emails.EmailController.java
/** * Send an email based on json payload. Recipient should be present in LDAP directory or in configured whitelist. * * Json sent should have following keys : * * - to : json array of email to send email to ex: ["you@rm.fr", "another-guy@rm.fr"] * - cc : json array of email to 'CC' email ex: ["him@rm.fr"] * - bcc : json array of email to add recipient as blind CC ["secret@rm.fr"] * - subject : subject of email// www . ja v a 2s .c o m * - body : Body of email * * Either 'to', 'cc' or 'bcc' parameter must be present in request. 'subject' and 'body' are mandatory. * * complete json example : * * { * "to": ["you@rm.fr", "another-guy@rm.fr"], * "cc": ["him@rm.fr"], * "bcc": ["secret@rm.fr"], * "subject": "test email", * "body": "Hi, this a test EMail, please do not reply." * } * */ @RequestMapping(value = "/emailProxy", method = RequestMethod.POST, produces = "application/json; charset=utf-8", consumes = "application/json") @ResponseBody public String emailProxy(@RequestBody String rawRequest, HttpServletRequest request) throws JSONException, MessagingException, UnsupportedEncodingException, DataServiceException { JSONObject payload = new JSONObject(rawRequest); InternetAddress[] to = this.populateRecipient("to", payload); InternetAddress[] cc = this.populateRecipient("cc", payload); InternetAddress[] bcc = this.populateRecipient("bcc", payload); this.checkSubject(payload); this.checkBody(payload); this.checkRecipient(to, cc, bcc); LOG.info("EMail request : user=" + request.getHeader("sec-username") + " to=" + this.extractAddress("to", payload) + " cc=" + this.extractAddress("cc", payload) + " bcc=" + this.extractAddress("bcc", payload) + " roles=" + request.getHeader("sec-roles")); LOG.debug("EMail request : " + payload.toString()); // Instanciate MimeMessage final Session session = Session.getInstance(System.getProperties(), null); session.getProperties().setProperty("mail.smtp.host", this.emailFactory.getSmtpHost()); session.getProperties().setProperty("mail.smtp.port", (new Integer(this.emailFactory.getSmtpPort())).toString()); MimeMessage message = new MimeMessage(session); // Generate From header InternetAddress from = new InternetAddress(); from.setAddress(this.georConfig.getProperty("emailProxyFromAddress")); from.setPersonal(request.getHeader("sec-firstname") + " " + request.getHeader("sec-lastname")); message.setFrom(from); // Generate Reply-to header InternetAddress replyTo = new InternetAddress(); replyTo.setAddress(request.getHeader("sec-email")); replyTo.setPersonal(request.getHeader("sec-firstname") + " " + request.getHeader("sec-lastname")); message.setReplyTo(new Address[] { replyTo }); // Generate to, cc and bcc headers if (to.length > 0) message.setRecipients(Message.RecipientType.TO, to); if (cc.length > 0) message.setRecipients(Message.RecipientType.CC, cc); if (bcc.length > 0) message.setRecipients(Message.RecipientType.BCC, bcc); // Add subject and body message.setSubject(payload.getString("subject"), "UTF-8"); message.setText(payload.getString("body"), "UTF-8", "plain"); message.setSentDate(new Date()); // finally send message Transport.send(message); JSONObject res = new JSONObject(); res.put("success", true); return res.toString(); }
From source file:org.georchestra.console.ws.emails.EmailController.java
/** * Send EmailEntry to smtp server//ww w. j av a 2s . co m * * @param email email to send * @throws NameNotFoundException if recipient cannot be found in LDAP server * @throws DataServiceException if LDAP server is not available * @throws MessagingException if some field of email cannot be encoded (malformed email address) */ private void send(EmailEntry email) throws NameNotFoundException, DataServiceException, MessagingException { final Session session = Session.getInstance(System.getProperties(), null); session.getProperties().setProperty("mail.smtp.host", this.emailFactory.getSmtpHost()); session.getProperties().setProperty("mail.smtp.port", (new Integer(this.emailFactory.getSmtpPort())).toString()); final MimeMessage message = new MimeMessage(session); Account recipient = this.accountDao.findByUID(email.getRecipient()); InternetAddress[] senders = { new InternetAddress(this.accountDao.findByUID(email.getSender()).getEmail()) }; message.addFrom(senders); message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient.getEmail())); message.setSubject(email.getSubject()); message.setHeader("Date", (new MailDateFormat()).format(email.getDate())); // Mail content Multipart multiPart = new MimeMultipart("alternative"); // attachments for (Attachment att : email.getAttachments()) { MimeBodyPart mbp = new MimeBodyPart(); mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(att.getContent(), att.getMimeType()))); mbp.setFileName(att.getName()); multiPart.addBodyPart(mbp); } // html part MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(email.getBody(), "text/html; charset=utf-8"); multiPart.addBodyPart(htmlPart); message.setContent(multiPart); // Send message Transport.send(message); }