List of usage examples for javax.mail Session getProperty
public String getProperty(String name)
From source file:com.liferay.util.mail.MailEngine.java
private static void _sendMessage(Session session, Message msg) throws MessagingException { boolean smtpAuth = GetterUtil.getBoolean(session.getProperty("mail.smtp.auth"), false); String smtpHost = session.getProperty("mail.smtp.host"); String user = session.getProperty("mail.smtp.user"); String password = session.getProperty("mail.smtp.password"); if (smtpAuth && Validator.isNotNull(user) && Validator.isNotNull(password)) { Transport tr = session.getTransport("smtp"); tr.connect(smtpHost, user, password); tr.sendMessage(msg, msg.getAllRecipients()); tr.close();/*from ww w .ja v a 2 s.c o m*/ } else { Transport.send(msg); } }
From source file:fr.gouv.culture.thesaurus.util.MailUtil.java
/** * Initialise les proprits statiques pour la gestion des emails. *///from www . j a v a2 s.c o m public static void init(String mailSessionJndiName, String defaultFrom, String subjectPrefix) { if (hostProperty == null) { Session mailSession; try { Context ctx = new InitialContext(); mailSession = (Session) ctx.lookup(mailSessionJndiName); hostProperty = mailSession.getProperty("mail.smtp.host"); } catch (NamingException e) { log.warn("Initialisation de la session email impossible.", e); } } MailUtil.defaultFrom = defaultFrom; MailUtil.subjectPrefix = subjectPrefix; }
From source file:com.sonicle.webtop.mail.Service.java
public Message reply(MailAccount account, MimeMessage orig, boolean replyToAll, boolean fromSent) throws MessagingException { MimeMessage reply = new MimeMessage(account.getMailSession()); /*//w ww.j a va 2 s.co m * Have to manipulate the raw Subject header so that we don't lose * any encoding information. This is safe because "Re:" isn't * internationalized and (generally) isn't encoded. If the entire * Subject header is encoded, prefixing it with "Re: " still leaves * a valid and correct encoded header. */ String subject = orig.getHeader("Subject", null); if (subject != null) { if (!subject.regionMatches(true, 0, "Re: ", 0, 4)) { subject = "Re: " + subject; } reply.setHeader("Subject", subject); } Address a[] = null; if (!fromSent) a = orig.getReplyTo(); else { Address ax[] = orig.getRecipients(RecipientType.TO); if (ax != null) { a = new Address[1]; a[0] = ax[0]; } } reply.setRecipients(Message.RecipientType.TO, a); if (replyToAll) { Vector v = new Vector(); Session session = account.getMailSession(); // add my own address to list InternetAddress me = InternetAddress.getLocalAddress(session); if (me != null) { v.addElement(me); } // add any alternate names I'm known by String alternates = null; if (session != null) { alternates = session.getProperty("mail.alternates"); } if (alternates != null) { eliminateDuplicates(v, InternetAddress.parse(alternates, false)); } // should we Cc all other original recipients? String replyallccStr = null; boolean replyallcc = false; if (session != null) { replyallcc = PropUtil.getBooleanSessionProperty(session, "mail.replyallcc", false); } // add the recipients from the To field so far eliminateDuplicates(v, a); a = orig.getRecipients(Message.RecipientType.TO); a = eliminateDuplicates(v, a); if (a != null && a.length > 0) { if (replyallcc) { reply.addRecipients(Message.RecipientType.CC, a); } else { reply.addRecipients(Message.RecipientType.TO, a); } } a = orig.getRecipients(Message.RecipientType.CC); a = eliminateDuplicates(v, a); if (a != null && a.length > 0) { reply.addRecipients(Message.RecipientType.CC, a); } // don't eliminate duplicate newsgroups a = orig.getRecipients(MimeMessage.RecipientType.NEWSGROUPS); if (a != null && a.length > 0) { reply.setRecipients(MimeMessage.RecipientType.NEWSGROUPS, a); } } String msgId = orig.getHeader("Message-Id", null); if (msgId != null) { reply.setHeader("In-Reply-To", msgId); } /* * Set the References header as described in RFC 2822: * * The "References:" field will contain the contents of the parent's * "References:" field (if any) followed by the contents of the parent's * "Message-ID:" field (if any). If the parent message does not contain * a "References:" field but does have an "In-Reply-To:" field * containing a single message identifier, then the "References:" field * will contain the contents of the parent's "In-Reply-To:" field * followed by the contents of the parent's "Message-ID:" field (if * any). If the parent has none of the "References:", "In-Reply-To:", * or "Message-ID:" fields, then the new message will have no * "References:" field. */ String refs = orig.getHeader("References", " "); if (refs == null) { // XXX - should only use if it contains a single message identifier refs = orig.getHeader("In-Reply-To", " "); } if (msgId != null) { if (refs != null) { refs = MimeUtility.unfold(refs) + " " + msgId; } else { refs = msgId; } } if (refs != null) { reply.setHeader("References", MimeUtility.fold(12, refs)); } //try { // setFlags(answeredFlag, true); //} catch (MessagingException mex) { // // ignore it //} return reply; }
From source file:org.exist.xquery.modules.mail.SendEmailFunction.java
public Sequence sendEmail(Sequence[] args, Sequence contextSequence) throws XPathException { // was a session handle specified? if (args[0].isEmpty()) { throw (new XPathException(this, "Session handle not specified")); }//from w ww . ja va 2s.c o m // get the Session long sessionHandle = ((IntegerValue) args[0].itemAt(0)).getLong(); Session session = MailModule.retrieveSession(context, sessionHandle); if (session == null) { throw (new XPathException(this, "Invalid Session handle specified")); } try { List<Message> messages = parseInputEmails(session, args[1]); String proto = session.getProperty("mail.transport.protocol"); if (proto == null) proto = "smtp"; Transport t = session.getTransport(proto); try { if (session.getProperty("mail." + proto + ".auth") != null) t.connect(session.getProperty("mail." + proto + ".user"), session.getProperty("mail." + proto + ".password")); for (Message msg : messages) { t.sendMessage(msg, msg.getAllRecipients()); } } finally { t.close(); } return (Sequence.EMPTY_SEQUENCE); } catch (TransformerException te) { throw new XPathException(this, "Could not Transform XHTML Message Body: " + te.getMessage(), te); } catch (MessagingException smtpe) { throw new XPathException(this, "Could not send message(s): " + smtpe.getMessage(), smtpe); } catch (IOException ioe) { throw new XPathException(this, "Attachment in some message could not be prepared: " + ioe.getMessage(), ioe); } catch (Throwable t) { throw new XPathException(this, "Unexpected error from JavaMail layer (Is your message well structured?): " + t.getMessage(), t); } }
From source file:org.exjello.mail.Exchange2003Connection.java
public static Exchange2003Connection createConnection(String protocol, Session session, String host, int port, String username, String password) throws Exception { String prefix = "mail." + protocol.toLowerCase() + "."; boolean debugPassword = Boolean.parseBoolean(session.getProperty(DEBUG_PASSWORD_PROPERTY)); String pwd = (password == null) ? null : debugPassword ? password : "<password>"; if (host == null || username == null || password == null) { if (session.getDebug()) { session.getDebugOut().println("Missing parameter; host=\"" + host + "\",username=\"" + username + "\",password=\"" + pwd + "\""); }/*from w ww . j a va 2 s . c om*/ throw new IllegalStateException("Host, username, and password must be specified."); } boolean unfiltered = Boolean.parseBoolean(session.getProperty(UNFILTERED_PROPERTY)); /* Mirco */ String filterLastCheck = session.getProperty(ExchangeConstants.FILTER_LAST_CHECK); String filterFrom = session.getProperty(ExchangeConstants.FILTER_FROM_PROPERTY); String filterNotFrom = session.getProperty(ExchangeConstants.FILTER_NOT_FROM_PROPERTY); String filterTo = session.getProperty(ExchangeConstants.FILTER_TO_PROPERTY); boolean delete = Boolean.parseBoolean(session.getProperty(DELETE_PROPERTY)); boolean secure = Boolean.parseBoolean(session.getProperty(prefix + SSL_PROPERTY)); int limit = -1; String limitString = session.getProperty(LIMIT_PROPERTY); if (limitString != null) { try { limit = Integer.parseInt(limitString); } catch (NumberFormatException ex) { throw new NumberFormatException("Invalid limit specified: " + limitString); } } try { URL url = new URL(host); // if parsing succeeded, then strip out the components and use secure = "https".equalsIgnoreCase(url.getProtocol()); host = url.getHost(); int specifiedPort = url.getPort(); if (specifiedPort != -1) port = specifiedPort; } catch (MalformedURLException ex) { if (session.getDebug()) { session.getDebugOut().println("Not parsing " + host + " as a URL; using explicit options for " + "secure, host, and port."); } } if (port == -1) { try { port = Integer.parseInt(session.getProperty(prefix + PORT_PROPERTY)); } catch (Exception ignore) { } if (port == -1) port = secure ? HTTPS_PORT : HTTP_PORT; } String server = (secure ? "https://" : "http://") + host; if (secure ? (port != HTTPS_PORT) : (port != HTTP_PORT)) { server += ":" + port; } String mailbox = session.getProperty(MAILBOX_PROPERTY); if (mailbox == null) { mailbox = session.getProperty(prefix + FROM_PROPERTY); if (mailbox == null) { mailbox = InternetAddress.getLocalAddress(session).getAddress(); } } int index = username.indexOf(':'); if (index != -1) { mailbox = username.substring(index + 1); username = username.substring(0, index); String mailboxOptions = null; index = mailbox.indexOf('['); if (index != -1) { mailboxOptions = mailbox.substring(index + 1); mailboxOptions = mailboxOptions.substring(0, mailboxOptions.indexOf(']')); mailbox = mailbox.substring(0, index); } if (mailboxOptions != null) { Properties props = null; try { props = parseOptions(mailboxOptions); } catch (Exception ex) { throw new IllegalArgumentException("Unable to parse mailbox options: " + ex.getMessage(), ex); } String value = props.getProperty("unfiltered"); if (value != null) unfiltered = Boolean.parseBoolean(value); /* Mirco */ value = props.getProperty("filterLastCheck"); if (value != null) filterLastCheck = value; value = props.getProperty("filterTo"); if (value != null) filterTo = value; value = props.getProperty("filterFrom"); if (value != null) filterFrom = value; value = props.getProperty("filterNotFrom"); if (value != null) filterNotFrom = value; value = props.getProperty("delete"); if (value != null) delete = Boolean.parseBoolean(value); value = props.getProperty("limit"); if (value != null) { try { limit = Integer.parseInt(value); } catch (NumberFormatException ex) { throw new NumberFormatException("Invalid limit specified: " + value); } } } else if (session.getDebug()) { session.getDebugOut().println( "No mailbox options specified; " + "using explicit limit, unfiltered, and delete."); } } else if (session.getDebug()) { session.getDebugOut().println("No mailbox specified in username; " + "using explicit mailbox, limit, unfiltered, and delete."); } int timeout = -1; String timeoutString = session.getProperty(prefix + TIMEOUT_PROPERTY); if (timeoutString != null) { try { timeout = Integer.parseInt(timeoutString); } catch (NumberFormatException ex) { throw new NumberFormatException("Invalid timeout value: " + timeoutString); } } int connectionTimeout = -1; timeoutString = session.getProperty(prefix + CONNECTION_TIMEOUT_PROPERTY); if (timeoutString != null) { try { connectionTimeout = Integer.parseInt(timeoutString); } catch (NumberFormatException ex) { throw new NumberFormatException("Invalid connection timeout value: " + timeoutString); } } InetAddress localAddress = null; String localAddressString = session.getProperty(prefix + LOCAL_ADDRESS_PROPERTY); if (localAddressString != null) { try { localAddress = InetAddress.getByName(localAddressString); } catch (Exception ex) { throw new UnknownHostException("Invalid local address specified: " + localAddressString); } } if (mailbox == null) { throw new IllegalStateException("No mailbox specified."); } if (session.getDebug()) { PrintStream debugStream = session.getDebugOut(); debugStream.println("Server:\t" + server); debugStream.println("Username:\t" + username); debugStream.println("Password:\t" + pwd); debugStream.println("Mailbox:\t" + mailbox); debugStream.print("Options:\t"); debugStream.print((limit > 0) ? "Message Limit = " + limit : "Unlimited Messages"); debugStream.print(unfiltered ? "; Unfiltered" : "; Filtered to Unread"); debugStream.print(filterLastCheck == null || "".equals(filterLastCheck) ? "; NO filterLastCheck" : "; Filtered after " + filterLastCheck); debugStream.print(filterFrom == null || "".equals(filterFrom) ? "; NO filterFromDomain" : "; Filtered from " + filterFrom); debugStream.print(filterNotFrom == null || "".equals(filterNotFrom) ? "; NO filterNotFrom" : "; Filtered not from " + filterNotFrom); debugStream.print( filterTo == null || "".equals(filterTo) ? "; NO filterToEmail" : "; Filtered to " + filterTo); debugStream.println(delete ? "; Delete Messages on Delete" : "; Mark as Read on Delete"); if (timeout > 0) { debugStream.println("Read timeout:\t" + timeout + " ms"); } if (connectionTimeout > 0) { debugStream.println("Connection timeout:\t" + connectionTimeout + " ms"); } } return new Exchange2003Connection(session, server, mailbox, username, password, timeout, connectionTimeout, localAddress, unfiltered, delete, limit, filterLastCheck, filterFrom, filterNotFrom, filterTo); }
From source file:org.exjello.mail.ExchangeConnection.java
public static ExchangeConnection createConnection(String protocol, Session session, String host, int port, String username, String password) throws Exception { String prefix = "mail." + protocol.toLowerCase() + "."; boolean debugPassword = Boolean.parseBoolean(session.getProperty(DEBUG_PASSWORD_PROPERTY)); String pwd = (password == null) ? null : debugPassword ? password : "<password>"; if (host == null || username == null || password == null) { if (session.getDebug()) { session.getDebugOut().println("Missing parameter; host=\"" + host + "\",username=\"" + username + "\",password=\"" + pwd + "\""); }/*from ww w .j av a2 s . com*/ throw new IllegalStateException("Host, username, and password must be specified."); } boolean unfiltered = Boolean.parseBoolean(session.getProperty(UNFILTERED_PROPERTY)); /* Mirco */ String filterLastCheck = session.getProperty(ExchangeConstants.FILTER_LAST_CHECK); String filterFrom = session.getProperty(ExchangeConstants.FILTER_FROM_PROPERTY); String filterNotFrom = session.getProperty(ExchangeConstants.FILTER_NOT_FROM_PROPERTY); String filterTo = session.getProperty(ExchangeConstants.FILTER_TO_PROPERTY); boolean delete = Boolean.parseBoolean(session.getProperty(DELETE_PROPERTY)); boolean secure = Boolean.parseBoolean(session.getProperty(prefix + SSL_PROPERTY)); int limit = -1; String limitString = session.getProperty(LIMIT_PROPERTY); if (limitString != null) { try { limit = Integer.parseInt(limitString); } catch (NumberFormatException ex) { throw new NumberFormatException("Invalid limit specified: " + limitString); } } try { URL url = new URL(host); // if parsing succeeded, then strip out the components and use secure = "https".equalsIgnoreCase(url.getProtocol()); host = url.getHost(); int specifiedPort = url.getPort(); if (specifiedPort != -1) port = specifiedPort; } catch (MalformedURLException ex) { if (session.getDebug()) { session.getDebugOut().println("Not parsing " + host + " as a URL; using explicit options for " + "secure, host, and port."); } } if (port == -1) { try { port = Integer.parseInt(session.getProperty(prefix + PORT_PROPERTY)); } catch (Exception ignore) { } if (port == -1) port = secure ? HTTPS_PORT : HTTP_PORT; } String server = (secure ? "https://" : "http://") + host; if (secure ? (port != HTTPS_PORT) : (port != HTTP_PORT)) { server += ":" + port; } String mailbox = session.getProperty(MAILBOX_PROPERTY); if (mailbox == null) { mailbox = session.getProperty(prefix + FROM_PROPERTY); if (mailbox == null) { mailbox = InternetAddress.getLocalAddress(session).getAddress(); } } int index = username.indexOf(':'); if (index != -1) { mailbox = username.substring(index + 1); username = username.substring(0, index); String mailboxOptions = null; index = mailbox.indexOf('['); if (index != -1) { mailboxOptions = mailbox.substring(index + 1); mailboxOptions = mailboxOptions.substring(0, mailboxOptions.indexOf(']')); mailbox = mailbox.substring(0, index); } if (mailboxOptions != null) { Properties props = null; try { props = parseOptions(mailboxOptions); } catch (Exception ex) { throw new IllegalArgumentException("Unable to parse mailbox options: " + ex.getMessage(), ex); } String value = props.getProperty("unfiltered"); if (value != null) unfiltered = Boolean.parseBoolean(value); /* Mirco */ value = props.getProperty("filterLastCheck"); if (value != null) filterLastCheck = value; value = props.getProperty("filterTo"); if (value != null) filterTo = value; value = props.getProperty("filterFrom"); if (value != null) filterFrom = value; value = props.getProperty("filterNotFrom"); if (value != null) filterNotFrom = value; value = props.getProperty("delete"); if (value != null) delete = Boolean.parseBoolean(value); value = props.getProperty("limit"); if (value != null) { try { limit = Integer.parseInt(value); } catch (NumberFormatException ex) { throw new NumberFormatException("Invalid limit specified: " + value); } } } else if (session.getDebug()) { session.getDebugOut().println( "No mailbox options specified; " + "using explicit limit, unfiltered, and delete."); } } else if (session.getDebug()) { session.getDebugOut().println("No mailbox specified in username; " + "using explicit mailbox, limit, unfiltered, and delete."); } int timeout = -1; String timeoutString = session.getProperty(prefix + TIMEOUT_PROPERTY); if (timeoutString != null) { try { timeout = Integer.parseInt(timeoutString); } catch (NumberFormatException ex) { throw new NumberFormatException("Invalid timeout value: " + timeoutString); } } int connectionTimeout = -1; timeoutString = session.getProperty(prefix + CONNECTION_TIMEOUT_PROPERTY); if (timeoutString != null) { try { connectionTimeout = Integer.parseInt(timeoutString); } catch (NumberFormatException ex) { throw new NumberFormatException("Invalid connection timeout value: " + timeoutString); } } InetAddress localAddress = null; String localAddressString = session.getProperty(prefix + LOCAL_ADDRESS_PROPERTY); if (localAddressString != null) { try { localAddress = InetAddress.getByName(localAddressString); } catch (Exception ex) { throw new UnknownHostException("Invalid local address specified: " + localAddressString); } } if (mailbox == null) { throw new IllegalStateException("No mailbox specified."); } if (session.getDebug()) { PrintStream debugStream = session.getDebugOut(); debugStream.println("Server:\t" + server); debugStream.println("Username:\t" + username); debugStream.println("Password:\t" + pwd); debugStream.println("Mailbox:\t" + mailbox); debugStream.print("Options:\t"); debugStream.print((limit > 0) ? "Message Limit = " + limit : "Unlimited Messages"); debugStream.print(unfiltered ? "; Unfiltered" : "; Filtered to Unread"); debugStream.print(filterLastCheck == null || "".equals(filterLastCheck) ? "; NO filterLastCheck" : "; Filtered after " + filterLastCheck); debugStream.print(filterFrom == null || "".equals(filterFrom) ? "; NO filterFromDomain" : "; Filtered from " + filterFrom); debugStream.print(filterNotFrom == null || "".equals(filterNotFrom) ? "; NO filterNotFrom" : "; Filtered not from " + filterNotFrom); debugStream.print( filterTo == null || "".equals(filterTo) ? "; NO filterToEmail" : "; Filtered to " + filterTo); debugStream.println(delete ? "; Delete Messages on Delete" : "; Mark as Read on Delete"); if (timeout > 0) { debugStream.println("Read timeout:\t" + timeout + " ms"); } if (connectionTimeout > 0) { debugStream.println("Connection timeout:\t" + connectionTimeout + " ms"); } } return new ExchangeConnection(session, server, mailbox, username, password, timeout, connectionTimeout, localAddress, unfiltered, delete, limit, filterLastCheck, filterFrom, filterNotFrom, filterTo); }
From source file:org.nuxeo.ecm.platform.ec.notification.email.EmailHelper.java
protected void sendmail0(Map<String, Object> mail) throws MessagingException, IOException, TemplateException, LoginException, RenderingException { Session session = getSession(); if (javaMailNotAvailable || session == null) { log.warn("Not sending email since JavaMail is not configured"); return;// ww w. j a v a 2s . co m } // Construct a MimeMessage MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(session.getProperty("mail.from"))); Object to = mail.get("mail.to"); if (!(to instanceof String)) { log.error("Invalid email recipient: " + to); return; } msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse((String) to, false)); RenderingService rs = Framework.getService(RenderingService.class); DocumentRenderingContext context = new DocumentRenderingContext(); context.remove("doc"); context.putAll(mail); context.setDocument((DocumentModel) mail.get("document")); context.put("Runtime", Framework.getRuntime()); String customSubjectTemplate = (String) mail.get(NotificationConstants.SUBJECT_TEMPLATE_KEY); if (customSubjectTemplate == null) { String subjTemplate = (String) mail.get(NotificationConstants.SUBJECT_KEY); Template templ = new Template("name", new StringReader(subjTemplate), stringCfg); Writer out = new StringWriter(); templ.process(mail, out); out.flush(); msg.setSubject(out.toString(), "UTF-8"); } else { rs.registerEngine(new NotificationsRenderingEngine(customSubjectTemplate)); LoginContext lc = Framework.login(); Collection<RenderingResult> results = rs.process(context); String subjectMail = "<HTML><P>No parsing Succeded !!!</P></HTML>"; for (RenderingResult result : results) { subjectMail = (String) result.getOutcome(); } subjectMail = NotificationServiceHelper.getNotificationService().getEMailSubjectPrefix() + subjectMail; msg.setSubject(subjectMail, "UTF-8"); lc.logout(); } msg.setSentDate(new Date()); rs.registerEngine(new NotificationsRenderingEngine((String) mail.get(NotificationConstants.TEMPLATE_KEY))); LoginContext lc = Framework.login(); Collection<RenderingResult> results = rs.process(context); String bodyMail = "<HTML><P>No parsing Succedeed !!!</P></HTML>"; for (RenderingResult result : results) { bodyMail = (String) result.getOutcome(); } lc.logout(); rs.unregisterEngine("ftl"); msg.setContent(bodyMail, "text/html; charset=utf-8"); // Send the message. Transport.send(msg); }
From source file:org.nuxeo.ecm.user.invite.UserInvitationComponent.java
protected void generateMail(String destination, String copy, String title, String content) throws NamingException, MessagingException { InitialContext ic = new InitialContext(); Session session = (Session) ic.lookup(getJavaMailJndiName()); MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(session.getProperty("mail.from"))); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(destination, false)); if (!isBlank(copy)) { msg.addRecipient(Message.RecipientType.CC, new InternetAddress(copy, false)); }//w w w .ja v a 2 s. co m msg.setSubject(title, "UTF-8"); msg.setSentDate(new Date()); msg.setContent(content, "text/html; charset=utf-8"); Transport.send(msg); }
From source file:org.seedstack.javamail.internal.PropertyFileSessionConfigurerTest.java
@Test public void test_smtp_session_configuration_is_present() { assertThat(sessionsConfig).containsKey("smtp"); final Session smtp = sessionsConfig.get("smtp"); assertThat(smtp).isNotNull();//from w w w. j a v a 2 s . c om assertThat(smtp.getProperty("mail.smtp.host")).isEqualTo("testserver"); assertThat(smtp.getProperty("mail.smtp.auth")).isEqualTo("true"); assertThat(smtp.getProperty("mail.smtp.user")).isEqualTo("testuser"); assertThat(smtp.getProperty("mail.smtp.password")).isEqualTo("testpw"); }
From source file:org.seedstack.javamail.internal.PropertyFileSessionConfigurerTest.java
@Test public void test_smtp2_session_configuration_is_present() { assertThat(sessionsConfig).containsKey("smtp2"); final Session smtp2 = sessionsConfig.get("smtp2"); assertThat(smtp2).isNotNull();/*w w w . j a va2 s . c o m*/ assertThat(smtp2.getProperty("mail.smtp.host")).isEqualTo("testserver2"); assertThat(smtp2.getProperty("mail.smtp.auth")).isEqualTo("true"); assertThat(smtp2.getProperty("mail.smtp.user")).isEqualTo("testuser2"); assertThat(smtp2.getProperty("mail.smtp.password")).isEqualTo("testpw2"); }