List of usage examples for javax.mail Session setDebug
public synchronized void setDebug(boolean debug)
From source file:org.xwiki.contrib.mail.internal.DefaultMailReader.java
private Session createSession(final String protocol, final Properties additionalProperties, final boolean isGmail, final boolean autoTrustSsl) { // Get a session. Use a blank Properties object. Properties props = new Properties(additionalProperties); // necessary to work with Gmail if (isGmail && !props.containsKey("mail.imap.partialfetch") && !props.containsKey("mail.imaps.partialfetch")) { props.put("mail.imap.partialfetch", "false"); props.put("mail.imaps.partialfetch", "false"); }//from w ww.j a va 2 s .com props.put("mail.store.protocol", protocol); // TODO set this as an option (auto-trust certificates for SSL) props.put("mail.imap.ssl.checkserveridentity", "false"); props.put("mail.imaps.ssl.trust", "*"); /* * MailSSLSocketFactory socketFactory = new MailSSLSocketFactory(); socketFactory.setTrustAllHosts(true); * props.put("mail.imaps.ssl.socketFactory", socketFactory); */ Session session = Session.getInstance(props, null); session.setDebug(true); return session; }
From source file:com.szmslab.quickjavamail.receive.MailReceiver.java
/** * ????/*ww w . j a va 2 s. c om*/ * * @param callback * ??1??? * @throws Exception */ public void execute(ReceiveIterationCallback callback) throws Exception { final Session session = useDefaultSession ? Session.getDefaultInstance(properties.getProperties(), properties.getAuthenticator()) : Session.getInstance(properties.getProperties(), properties.getAuthenticator()); session.setDebug(isDebug); Store store = null; Folder folder = null; try { store = session.getStore(properties.getProtocol()); store.connect(); folder = store.getFolder(folderName); folder.open(readonly ? Folder.READ_ONLY : Folder.READ_WRITE); final Message messages[] = folder.getMessages(); for (Message message : messages) { MessageLoader loader = new MessageLoader(message, !readonly); boolean isContinued = callback.iterate(loader); if (!readonly && loader.isDeleted()) { message.setFlag(Flags.Flag.DELETED, loader.isDeleted()); } if (!isContinued) { break; } } } finally { if (folder != null) { try { folder.close(!readonly); } catch (MessagingException e) { System.out.println(e); } } if (store != null) { try { store.close(); } catch (MessagingException e) { System.out.println(e); } } } }
From source file:org.linagora.linshare.core.service.impl.MailNotifierServiceImpl.java
/** * Create some properties and get the default Session */// w w w . ja va 2 s . c o m private Session getMailSession() { // Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", smtpServer); props.put("mail.smtp.port", smtpPort + ""); if (needsAuth) { props.put("mail.smtp.auth", "true"); } else { props.put("mail.smtp.auth", "false"); } // create some properties and get the default Session Session session = Session.getInstance(props, null); if (logger.isDebugEnabled()) { session.setDebug(true); } else { session.setDebug(false); } return session; }
From source file:org.collectionspace.chain.csp.persistence.file.TestGeneral.java
/** * Sets up and sends email message providing you have set up the email address to send to *//* w w w . j av a2s . com*/ @Test public void testEmail() { Boolean doIreallyWantToSpam = false; // set to true when you have configured the email addresses /* please personalises these emails before sending - I don't want your spam. */ String from = "admin@collectionspace.org"; String[] recipients = { "" }; String SMTP_HOST_NAME = "localhost"; String SMTP_PORT = "25"; String message = "Hi, Test Message Contents"; String subject = "A test from collectionspace test suite"; String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); //REM - Replace. This is pre-JDK 1.4 code, from the days when JSSE was a separate download. Fix the imports so they refer to the classes in javax.net.ssl If you really want to get hold of a specific instance, you can use Security.getProvider(name). You'll find the appropriate names in the providers documentation. boolean debug = true; Properties props = new Properties(); props.put("mail.smtp.host", SMTP_HOST_NAME); //props.put("mail.smtp.auth", "true"); props.put("mail.smtp.auth", "false"); props.put("mail.debug", "true"); props.put("mail.smtp.port", SMTP_PORT); props.put("mail.smtp.socketFactory.port", SMTP_PORT); props.put("mail.smtp.socketFactory.class", SSL_FACTORY); props.put("mail.smtp.socketFactory.fallback", "false"); Session session = Session.getDefaultInstance(props); session.setDebug(debug); if (doIreallyWantToSpam) { Message msg = new MimeMessage(session); InternetAddress addressFrom; try { addressFrom = new InternetAddress(from); msg.setFrom(addressFrom); InternetAddress[] addressTo = new InternetAddress[recipients.length]; for (int i = 0; i < recipients.length; i++) { addressTo[i] = new InternetAddress(recipients[i]); } msg.setRecipients(Message.RecipientType.TO, addressTo); // Setting the Subject and Content Type msg.setSubject(subject); msg.setContent(message, "text/plain"); if (doIreallyWantToSpam) { Transport.send(msg); assertTrue(doIreallyWantToSpam); } } catch (AddressException e) { log.debug(e.getMessage()); assertTrue(false); } catch (MessagingException e) { log.debug(e.getMessage()); assertTrue(false); } } //assertTrue(doIreallyWantToSpam); }
From source file:com.bizintelapps.cars.service.impl.EmailServiceImpl.java
/** * // w w w. j a v a 2 s . c om * @param recipients * @param subject * @param message * @param from * @throws MessagingException */ private void sendSSMessage(String recipients[], String subject, Car car, String comment) { try { InternetAddress[] addressTo = new InternetAddress[recipients.length]; for (int i = 0; i < recipients.length; i++) { if (recipients[i] != null && recipients[i].length() > 0) { addressTo[i] = new InternetAddress(recipients[i]); } } if (addressTo == null || addressTo.length == 0) { return; } boolean debug = true; Properties props = new Properties(); props.put("mail.smtp.host", SMTP_HOST_NAME); props.put("mail.smtp.auth", "true"); props.put("mail.debug", "true"); props.put("mail.smtp.port", SMTP_PORT); props.put("mail.smtp.socketFactory.port", SMTP_PORT); props.put("mail.smtp.socketFactory.class", SSL_FACTORY); props.put("mail.smtp.socketFactory.fallback", "false"); Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(SEND_FROM_USERNAME, SEND_FROM_PASSWORD); } }); session.setDebug(debug); Message msg = new MimeMessage(session); InternetAddress addressFrom = new InternetAddress(EMAIL_FROM_ADDRESS); msg.setFrom(addressFrom); msg.setRecipients(Message.RecipientType.TO, addressTo); // Setting the Subject and Content Type msg.setSubject(subject); String message = buildMessage(car, comment); msg.setContent(message, EMAIL_CONTENT_TYPE); Transport.send(msg); } catch (Exception ex) { logger.warn(ex.getMessage(), ex); throw new RuntimeException("Error sending email, please check to and from emails are correct!"); } }
From source file:org.sakaiproject.tool.assessment.util.SamigoEmailService.java
public String sendMail() { try {//from w ww. j av a 2 s . c o m Properties props = new Properties(); // Server if (smtpServer == null || smtpServer.equals("")) { log.info("samigo.email.smtpServer is not set"); smtpServer = ServerConfigurationService.getString("smtp@org.sakaiproject.email.api.EmailService"); if (smtpServer == null || smtpServer.equals("")) { log.info("smtp@org.sakaiproject.email.api.EmailService is not set"); log.error( "Please set the value of samigo.email.smtpServer or smtp@org.sakaiproject.email.api.EmailService"); return "error"; } } props.setProperty("mail.smtp.host", smtpServer); // Port if (smtpPort == null || smtpPort.equals("")) { log.warn("samigo.email.smtpPort is not set. The default port 25 will be used."); } else { props.setProperty("mail.smtp.port", smtpPort); } props.put("mail.smtp.sendpartial", "true"); Session session = Session.getInstance(props, null); session.setDebug(true); MimeMessage msg = new MimeMessage(session); InternetAddress fromIA = new InternetAddress(fromEmailAddress, fromName); msg.setFrom(fromIA); //msg.addHeaderLine("Subject: " + subject); msg.setSubject(subject, "UTF-8"); String noReplyEmaillAddress = ServerConfigurationService.getString("setup.request", "no-reply@" + ServerConfigurationService.getServerName()); msg.addHeaderLine("To: " + noReplyEmaillAddress); msg.setText(message, "UTF-8"); msg.addHeaderLine("Content-Type: text/html"); ArrayList<InternetAddress> toIAList = new ArrayList<InternetAddress>(); String email = ""; Iterator iter = toEmailAddressList.iterator(); while (iter.hasNext()) { try { email = (String) iter.next(); toIAList.add(new InternetAddress(email)); } catch (AddressException ae) { log.error("invalid email address: " + email); } } InternetAddress[] toIA = new InternetAddress[toIAList.size()]; int count = 0; Iterator iter2 = toIAList.iterator(); while (iter2.hasNext()) { toIA[count++] = (InternetAddress) iter2.next(); } try { Transport transport = session.getTransport("smtp"); msg.saveChanges(); transport.connect(); try { transport.sendMessage(msg, toIA); } catch (SendFailedException e) { log.debug("SendFailedException: " + e); return "error"; } catch (MessagingException e) { log.warn("1st MessagingException: " + e); return "error"; } transport.close(); } catch (MessagingException e) { log.warn("2nd MessagingException:" + e); return "error"; } } catch (UnsupportedEncodingException ue) { log.warn("UnsupportedEncodingException:" + ue); ue.printStackTrace(); } catch (MessagingException me) { log.warn("3rd MessagingException:" + me); return "error"; } return "send"; }
From source file:io.uengine.mail.MailAsyncService.java
private Session setMailProperties(final String toUser) { Properties props = new Properties(); props.put("mail.smtp.auth", auth); props.put("mail.smtp.starttls.enable", starttls); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); LogOutputStream loggerToStdOut = new LogOutputStream() { @Override//ww w.ja v a2 s. c o m protected void processLine(String line, int level) { logger.debug("[JavaMail] [{}] {}", toUser, line); } }; Session session = Session.getInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(account, password); } }); session.setDebug(true); session.setDebugOut(new PrintStream(loggerToStdOut)); return session; }
From source file:org.apache.synapse.transport.mail.MailEchoRawXMLTest.java
private Object getMessage(String requestMsgId) { Session session = Session.getInstance(props, null); session.setDebug(log.isTraceEnabled()); Store store = null;// w ww . ja v a2s . co m try { store = session.getStore("pop3"); store.connect(username, password); Folder folder = store.getFolder(MailConstants.DEFAULT_FOLDER); folder.open(Folder.READ_WRITE); Message[] msgs = folder.getMessages(); log.debug(msgs.length + " replies in reply mailbox"); for (Message m : msgs) { String[] inReplyTo = m.getHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO); log.debug("Got reply to : " + Arrays.toString(inReplyTo)); if (inReplyTo != null && inReplyTo.length > 0) { for (int j = 0; j < inReplyTo.length; j++) { if (requestMsgId.equals(inReplyTo[j])) { m.setFlag(Flags.Flag.DELETED, true); return m.getContent(); } } } m.setFlag(Flags.Flag.DELETED, true); } folder.close(true); } catch (Exception e) { e.printStackTrace(); } finally { if (store != null) { try { store.close(); } catch (MessagingException ignore) { } store = null; } } return null; }
From source file:org.sakaiproject.tool.assessment.util.SamigoEmailService.java
public String send() { List attachmentList = null;// ww w . j ava 2 s . c o m AttachmentData a = null; try { Properties props = new Properties(); // Server if (smtpServer == null || smtpServer.equals("")) { log.info("samigo.email.smtpServer is not set"); smtpServer = ServerConfigurationService.getString("smtp@org.sakaiproject.email.api.EmailService"); if (smtpServer == null || smtpServer.equals("")) { log.info("smtp@org.sakaiproject.email.api.EmailService is not set"); log.error( "Please set the value of samigo.email.smtpServer or smtp@org.sakaiproject.email.api.EmailService"); return "error"; } } props.setProperty("mail.smtp.host", smtpServer); // Port if (smtpPort == null || smtpPort.equals("")) { log.warn("samigo.email.smtpPort is not set. The default port 25 will be used."); } else { props.setProperty("mail.smtp.port", smtpPort); } Session session; session = Session.getInstance(props); session.setDebug(true); MimeMessage msg = new MimeMessage(session); InternetAddress fromIA = new InternetAddress(fromEmailAddress, fromName); msg.setFrom(fromIA); InternetAddress[] toIA = { new InternetAddress(toEmailAddress, toName) }; msg.setRecipients(Message.RecipientType.TO, toIA); if ("yes".equals(ccMe)) { InternetAddress[] ccIA = { new InternetAddress(fromEmailAddress, fromName) }; msg.setRecipients(Message.RecipientType.CC, ccIA); } msg.setSubject(subject); EmailBean emailBean = (EmailBean) ContextUtil.lookupBean("email"); attachmentList = emailBean.getAttachmentList(); StringBuilder content = new StringBuilder(message); ArrayList fileList = new ArrayList(); ArrayList fileNameList = new ArrayList(); if (attachmentList != null) { if (prefixedPath == null || prefixedPath.equals("")) { log.error("samigo.email.prefixedPath is not set"); return "error"; } Iterator iter = attachmentList.iterator(); while (iter.hasNext()) { a = (AttachmentData) iter.next(); if (a.getIsLink().booleanValue()) { log.debug("send(): url"); content.append("<br/>\n\r"); content.append("<br/>"); // give a new line content.append(a.getFilename()); } else { log.debug("send(): file"); File attachedFile = getAttachedFile(a.getResourceId()); fileList.add(attachedFile); fileNameList.add(a.getFilename()); } } } Multipart multipart = new MimeMultipart(); MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(content.toString(), "text/html"); multipart.addBodyPart(messageBodyPart); msg.setContent(multipart); for (int i = 0; i < fileList.size(); i++) { messageBodyPart = new MimeBodyPart(); FileDataSource source = new FileDataSource((File) fileList.get(i)); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName((String) fileNameList.get(i)); multipart.addBodyPart(messageBodyPart); } msg.setContent(multipart); Transport.send(msg); } catch (UnsupportedEncodingException e) { log.error("Exception throws from send()" + e.getMessage()); return "error"; } catch (MessagingException e) { log.error("Exception throws from send()" + e.getMessage()); return "error"; } catch (ServerOverloadException e) { log.error("Exception throws from send()" + e.getMessage()); return "error"; } catch (PermissionException e) { log.error("Exception throws from send()" + e.getMessage()); return "error"; } catch (IdUnusedException e) { log.error("Exception throws from send()" + e.getMessage()); return "error"; } catch (TypeException e) { log.error("Exception throws from send()" + e.getMessage()); return "error"; } catch (IOException e) { log.error("Exception throws from send()" + e.getMessage()); return "error"; } finally { if (attachmentList != null) { if (prefixedPath != null && !prefixedPath.equals("")) { StringBuilder sbPrefixedPath; Iterator iter = attachmentList.iterator(); while (iter.hasNext()) { sbPrefixedPath = new StringBuilder(prefixedPath); sbPrefixedPath.append("/email_tmp/"); a = (AttachmentData) iter.next(); if (!a.getIsLink().booleanValue()) { deleteAttachedFile(sbPrefixedPath.append(a.getResourceId()).toString()); } } } } } return "send"; }
From source file:org.apache.jmeter.reporters.MailerModel.java
/** * Sends a mail with the given parameters using SMTP. * * @param from//from w w w.j av a2 s. c om * the sender of the mail as shown in the mail-client. * @param vEmails * all receivers of the mail. The receivers are seperated by * commas. * @param subject * the subject of the mail. * @param attText * the message-body. * @param smtpHost * the smtp-server used to send the mail. * @param smtpPort the smtp-server port used to send the mail. * @param user the login used to authenticate * @param password the password used to authenticate * @param mailAuthType {@link MailAuthType} Security policy * @param debug Flag whether debug messages for the mail session should be generated * @throws AddressException If mail address is wrong * @throws MessagingException If building MimeMessage fails */ public void sendMail(String from, List<String> vEmails, String subject, String attText, String smtpHost, String smtpPort, final String user, final String password, MailAuthType mailAuthType, boolean debug) throws AddressException, MessagingException { InternetAddress[] address = new InternetAddress[vEmails.size()]; for (int k = 0; k < vEmails.size(); k++) { address[k] = new InternetAddress(vEmails.get(k)); } // create some properties and get the default Session Properties props = new Properties(); props.put(MAIL_SMTP_HOST, smtpHost); props.put(MAIL_SMTP_PORT, smtpPort); // property values are strings Authenticator authenticator = null; if (mailAuthType != MailAuthType.NONE) { props.put(MAIL_SMTP_AUTH, "true"); switch (mailAuthType) { case SSL: props.put(MAIL_SMTP_SOCKETFACTORY_CLASS, "javax.net.ssl.SSLSocketFactory"); break; case TLS: props.put(MAIL_SMTP_STARTTLS, "true"); break; default: break; } } if (!StringUtils.isEmpty(user)) { authenticator = new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(user, password); } }; } Session session = Session.getInstance(props, authenticator); session.setDebug(debug); // create a message Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); msg.setRecipients(Message.RecipientType.TO, address); msg.setSubject(subject); msg.setText(attText); Transport.send(msg); }