List of usage examples for javax.mail Session getDefaultInstance
public static synchronized Session getDefaultInstance(Properties props, Authenticator authenticator)
From source file:at.gv.egovernment.moa.id.configuration.helper.MailHelper.java
private static void sendMail(ConfigurationProvider config, String subject, String recipient, String content) throws ConfigurationException { try {/*from ww w . j a v a 2 s. com*/ log.debug("Sending mail."); MiscUtil.assertNotNull(subject, "subject"); MiscUtil.assertNotNull(recipient, "recipient"); MiscUtil.assertNotNull(content, "content"); Properties props = new Properties(); props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.host", config.getSMTPMailHost()); log.trace("Mail host: " + config.getSMTPMailHost()); if (config.getSMTPMailPort() != null) { log.trace("Mail port: " + config.getSMTPMailPort()); props.setProperty("mail.port", config.getSMTPMailPort()); } if (config.getSMTPMailUsername() != null) { log.trace("Mail user: " + config.getSMTPMailUsername()); props.setProperty("mail.user", config.getSMTPMailUsername()); } if (config.getSMTPMailPassword() != null) { log.trace("Mail password: " + config.getSMTPMailPassword()); props.setProperty("mail.password", config.getSMTPMailPassword()); } Session mailSession = Session.getDefaultInstance(props, null); Transport transport = mailSession.getTransport(); MimeMessage message = new MimeMessage(mailSession); message.setSubject(subject); log.trace("Mail from: " + config.getMailFromName() + "/" + config.getMailFromAddress()); message.setFrom(new InternetAddress(config.getMailFromAddress(), config.getMailFromName())); log.trace("Recipient: " + recipient); message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient)); log.trace("Creating multipart content of mail."); MimeMultipart multipart = new MimeMultipart("related"); log.trace("Adding first part (html)"); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(content, "text/html; charset=ISO-8859-15"); multipart.addBodyPart(messageBodyPart); // log.trace("Adding mail images"); // messageBodyPart = new MimeBodyPart(); // for (Image image : images) { // messageBodyPart.setDataHandler(new DataHandler(image)); // messageBodyPart.setHeader("Content-ID", "<" + image.getContentId() + ">"); // multipart.addBodyPart(messageBodyPart); // } message.setContent(multipart); transport.connect(); log.trace("Sending mail message."); transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO)); log.trace("Successfully sent."); transport.close(); } catch (MessagingException e) { throw new ConfigurationException(e); } catch (UnsupportedEncodingException e) { throw new ConfigurationException(e); } }
From source file:pt.lsts.neptus.comm.iridium.RockBlockIridiumMessenger.java
@Override public Collection<IridiumMessage> pollMessages(Date timeSince) throws Exception { if (askGmailPassword || gmailPassword == null || gmailUsername == null) { Pair<String, String> credentials = GuiUtils.askCredentials(ConfigFetch.getSuperParentFrame(), "Enter Gmail Credentials", getGmailUsername(), getGmailPassword()); if (credentials == null) return null; setGmailUsername(credentials.first()); setGmailPassword(credentials.second()); PluginUtils.saveProperties("conf/rockblock.props", this); askGmailPassword = false;/*w w w.j av a2 s .c om*/ } Properties props = new Properties(); props.put("mail.store.protocol", "imaps"); ArrayList<IridiumMessage> messages = new ArrayList<>(); try { Session session = Session.getDefaultInstance(props, null); Store store = session.getStore("imaps"); store.connect("imap.gmail.com", getGmailUsername(), getGmailPassword()); Folder inbox = store.getFolder("Inbox"); inbox.open(Folder.READ_ONLY); int numMsgs = inbox.getMessageCount(); for (int i = numMsgs; i > 0; i--) { Message m = inbox.getMessage(i); if (m.getReceivedDate().before(timeSince)) { break; } else { MimeMultipart mime = (MimeMultipart) m.getContent(); for (int j = 0; j < mime.getCount(); j++) { BodyPart p = mime.getBodyPart(j); Matcher matcher = pattern.matcher(p.getContentType()); if (matcher.matches()) { InputStream stream = (InputStream) p.getContent(); byte[] data = IOUtils.toByteArray(stream); IridiumMessage msg = process(data, matcher.group(1)); if (msg != null) messages.add(msg); } } } } } catch (NoSuchProviderException ex) { ex.printStackTrace(); System.exit(1); } catch (MessagingException ex) { ex.printStackTrace(); System.exit(2); } return messages; }
From source file:org.bibsonomy.util.MailUtils.java
/** * Sends a mail to the given recipients/* ww w .ja v a 2 s . c om*/ * * @param recipients * @param subject * @param message * @param from * @throws MessagingException */ private void sendMail(final String[] recipients, final String subject, final String message, final String from) throws MessagingException { boolean debug = false; // create some properties and get the default Session final Session session = Session.getDefaultInstance(props, null); session.setDebug(debug); // create a message final MimeMessage msg = new MimeMessage(session); // set the from and to address final InternetAddress addressFrom = new InternetAddress(from); msg.setFrom(addressFrom); final 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); // Optional : You can also set your custom headers in the Email if you Want //msg.addHeader("X-Sent-By", "Bibsonomy-Bot"); // Setting the Subject and Content Type msg.setSubject(subject); msg.setText(message, "UTF-8"); Transport.send(msg); }
From source file:pt.ist.fenixedu.integration.task.exportData.parking.ExportCarParkUsers.java
private void sendParkingInfoToRemoteCarPark(String filename, byte[] byteArray) throws AddressException, MessagingException { final Properties properties = new Properties(); properties.put("mail.smtp.host", FenixEduAcademicConfiguration.getConfiguration().getMailSmtpHost()); properties.put("mail.smtp.name", FenixEduAcademicConfiguration.getConfiguration().getMailSmtpName()); properties.put("mailSender.max.recipients", FenixEduAcademicConfiguration.getConfiguration().getMailSenderMaxRecipients()); properties.put("mail.debug", "false"); final Session session = Session.getDefaultInstance(properties, null); final Sender sender = Bennu.getInstance().getSystemSender(); final Message message = new MimeMessage(session); message.setFrom(new InternetAddress(sender.getFromAddress())); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(EMAIL_ADDRESSES_TO_SEND_DATA)); message.setSubject("Utentes IST - Atualizao"); message.setText("Listagem atualizada de utentes do IST: " + new DateTime().toString("yyyy-MM-dd HH:mm")); MimeBodyPart messageBodyPart = new MimeBodyPart(); Multipart multipart = new MimeMultipart(); messageBodyPart = new MimeBodyPart(); DataSource source = new ByteArrayDataSource(byteArray, "text/plain"); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); message.setContent(multipart);//from w w w. j av a 2 s. com Transport.send(message); }
From source file:org.openmeetings.test.calendar.TestSendIcalMessage.java
private void sendIcalMessage() throws Exception { log.debug("sendIcalMessage"); // Evaluating Configuration Data String smtpServer = cfgManagement.getConfKey(3, "smtp_server").getConf_value(); String smtpPort = cfgManagement.getConfKey(3, "smtp_port").getConf_value(); // String from = "openmeetings@xmlcrm.org"; String from = cfgManagement.getConfKey(3, "system_email_addr").getConf_value(); String emailUsername = cfgManagement.getConfKey(3, "email_username").getConf_value(); String emailUserpass = cfgManagement.getConfKey(3, "email_userpass").getConf_value(); Properties props = System.getProperties(); props.put("mail.smtp.host", smtpServer); props.put("mail.smtp.port", smtpPort); Configuration conf = cfgManagement.getConfKey(3, "mail.smtp.starttls.enable"); if (conf != null) { if (conf.getConf_value().equals("1")) { props.put("mail.smtp.starttls.enable", "true"); }//from w w w. ja v a 2s. com } // Check for Authentification Session session = null; if (emailUsername != null && emailUsername.length() > 0 && emailUserpass != null && emailUserpass.length() > 0) { // use SMTP Authentication props.put("mail.smtp.auth", "true"); session = Session.getDefaultInstance(props, new SmtpAuthenticator(emailUsername, emailUserpass)); } else { // not use SMTP Authentication session = Session.getDefaultInstance(props, null); } // Building MimeMessage MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setSubject(subject); mimeMessage.setFrom(new InternetAddress(from)); mimeMessage.addRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients, false)); // -- Create a new message -- BodyPart msg = new MimeBodyPart(); msg.setDataHandler(new DataHandler(new ByteArrayDataSource(htmlBody, "text/html; charset=\"utf-8\""))); Multipart multipart = new MimeMultipart(); BodyPart iCalAttachment = new MimeBodyPart(); iCalAttachment.setDataHandler(new DataHandler(new javax.mail.util.ByteArrayDataSource( new ByteArrayInputStream(iCalMimeBody), "text/calendar;method=REQUEST;charset=\"UTF-8\""))); iCalAttachment.setFileName("invite.ics"); multipart.addBodyPart(iCalAttachment); multipart.addBodyPart(msg); mimeMessage.setSentDate(new Date()); mimeMessage.setContent(multipart); // -- Set some other header information -- // mimeMessage.setHeader("X-Mailer", "XML-Mail"); // mimeMessage.setSentDate(new Date()); // Transport trans = session.getTransport("smtp"); Transport.send(mimeMessage); }
From source file:org.wso2.carbon.registry.es.utils.EmailUtil.java
/** * This method delete all the sent mails. Can be used after a particular test class * * @throws MessagingException/* ww w. j av a 2 s .c o m*/ * @throws IOException */ public static void deleteSentMails() throws MessagingException, IOException { Properties props = new Properties(); props.load(new FileInputStream(new File(TestConfigurationProvider.getResourceLocation("GREG") + File.separator + "axis2" + File.separator + "smtp.properties"))); Session session = Session.getDefaultInstance(props, null); Store store = session.getStore("imaps"); store.connect("smtp.gmail.com", emailAddress, java.nio.CharBuffer.wrap(emailPassword).toString()); Folder sentMail = store.getFolder("[Gmail]/Sent Mail"); sentMail.open(Folder.READ_WRITE); Message[] messages = sentMail.getMessages(); Flags deleted = new Flags(Flags.Flag.DELETED); sentMail.setFlags(messages, deleted, true); sentMail.close(true); store.close(); }
From source file:TestOpenMailRelay.java
/** Do the work: send the mail to the SMTP server. */ public void doSend() { // We need to pass info to the mail server as a Properties, since // JavaMail (wisely) allows room for LOTS of properties... Properties props = new Properties(); // Your LAN must define the local SMTP server as "mailhost" // for this simple-minded version to be able to send mail... props.put("mail.smtp.host", "mailhost"); // Create the Session object session = Session.getDefaultInstance(props, null); session.setDebug(true); // Verbose! try {/*w w w . jav a 2s. c om*/ // create a message mesg = new MimeMessage(session); // From Address - this should come from a Properties... mesg.setFrom(new InternetAddress("nobody@host.domain")); // TO Address InternetAddress toAddress = new InternetAddress(message_recip); mesg.addRecipient(Message.RecipientType.TO, toAddress); // CC Address InternetAddress ccAddress = new InternetAddress(message_cc); mesg.addRecipient(Message.RecipientType.CC, ccAddress); // The Subject mesg.setSubject(message_subject); // Now the message body. mesg.setText(message_body); // XXX I18N: use setText(msgText.getText(), charset) // Finally, send the message! Transport.send(mesg); } catch (MessagingException ex) { while ((ex = (MessagingException) ex.getNextException()) != null) { ex.printStackTrace(); } } }
From source file:eu.scape_project.planning.user.Groups.java
/** * Sends an invitation mail to the user. * //from w ww. jav a2 s . c o m * @param toUser * the recipient of the mail * @param serverString * the server string * @return true if the mail was sent successfully, false otherwise * @throws InvitationMailException * if the invitation mail could not be send */ private void sendInvitationMail(GroupInvitation invitation, String serverString) throws InvitationMailException { try { Properties props = System.getProperties(); props.put("mail.smtp.host", config.getString("mail.smtp.host")); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(config.getString("mail.from"))); message.setRecipient(RecipientType.TO, new InternetAddress(invitation.getEmail())); message.setSubject( user.getFullName() + " invited you to join the Plato group " + user.getUserGroup().getName()); StringBuilder builder = new StringBuilder(); builder.append("Hello, \n\n"); builder.append("The Plato user " + user.getFullName() + " has invited you to join the group " + user.getUserGroup().getName() + ".\n\n"); builder.append( "You do not seem to be a Plato user. If you would like to accept the invitation, please first create an account at http://" + serverString + "/idp/addUser.jsf.\n"); builder.append( "If you have an account, please log in and use the following link to accept the invitation: \n"); builder.append("http://" + serverString + "/plato/user/groupInvitation.jsf?uid=" + invitation.getInvitationActionToken()); builder.append("\n\n--\n"); builder.append("Your Planningsuite team"); message.setText(builder.toString()); message.saveChanges(); Transport.send(message); log.debug("Group invitation mail sent successfully to " + invitation.getEmail()); } catch (MessagingException e) { log.error("Error sending group invitation mail to " + invitation.getEmail(), e); throw new InvitationMailException(e); } }
From source file:org.agnitas.util.AgnUtils.java
/** * Sends an email in the correspondent type. *//*from www . j ava 2 s . c o m*/ public static boolean sendEmail(String from_adr, String to_adrList, String cc_adrList, String subject, String body_text, String body_html, int mailtype, String charset) { try { // create some properties and get the default Session Properties props = new Properties(); props.put("system.mail.host", getSmtpMailRelayHostname()); Session session = Session.getDefaultInstance(props, null); // session.setDebug(debug); // create a message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from_adr)); msg.setSubject(subject, charset); msg.setSentDate(new Date()); // Set to-recipient email addresses InternetAddress[] toAddresses = getEmailAddressesFromList(to_adrList); if (toAddresses != null && toAddresses.length > 0) { msg.setRecipients(Message.RecipientType.TO, toAddresses); } // Set cc-recipient email addresses InternetAddress[] ccAddresses = getEmailAddressesFromList(cc_adrList); if (ccAddresses != null && ccAddresses.length > 0) { msg.setRecipients(Message.RecipientType.CC, ccAddresses); } switch (mailtype) { case 0: msg.setText(body_text, charset); break; case 1: Multipart mp = new MimeMultipart("alternative"); MimeBodyPart mbp = new MimeBodyPart(); mbp.setText(body_text, charset); mp.addBodyPart(mbp); mbp = new MimeBodyPart(); mbp.setContent(body_html, "text/html; charset=" + charset); mp.addBodyPart(mbp); msg.setContent(mp); break; } Transport.send(msg); } catch (Exception e) { logger.error("sendEmail: " + e); logger.error(AgnUtils.getStackTrace(e)); return false; } return true; }
From source file:org.alfresco.repo.imap.ImapMessageTest.java
@Override public void setUp() throws Exception { logger.debug("In SetUp"); serviceRegistry = (ServiceRegistry) ctx.getBean("ServiceRegistry"); transactionService = serviceRegistry.getTransactionService(); nodeService = serviceRegistry.getNodeService(); importerService = serviceRegistry.getImporterService(); personService = serviceRegistry.getPersonService(); authenticationService = serviceRegistry.getAuthenticationService(); searchService = serviceRegistry.getSearchService(); namespaceService = serviceRegistry.getNamespaceService(); fileFolderService = serviceRegistry.getFileFolderService(); // start the transaction UserTransaction txn = transactionService.getUserTransaction(); txn.begin();/*w w w . j a v a 2 s . c o m*/ authenticationService.authenticate(ADMIN_USER_NAME, ADMIN_USER_PASSWORD.toCharArray()); // downgrade integrity IntegrityChecker.setWarnInTransaction(); anotherUserName = "user" + System.currentTimeMillis(); PropertyMap testUser = new PropertyMap(); testUser.put(ContentModel.PROP_USERNAME, anotherUserName); testUser.put(ContentModel.PROP_FIRSTNAME, anotherUserName); testUser.put(ContentModel.PROP_LASTNAME, anotherUserName); testUser.put(ContentModel.PROP_EMAIL, anotherUserName + "@alfresco.com"); testUser.put(ContentModel.PROP_JOBTITLE, "jobTitle"); personService.createPerson(testUser); // create the ACEGI Authentication instance for the new user authenticationService.createAuthentication(anotherUserName, anotherUserName.toCharArray()); StoreRef storeRef = new StoreRef(storePath); storeRootNodeRef = nodeService.getRootNode(storeRef); List<NodeRef> nodeRefs = searchService.selectNodes(storeRootNodeRef, companyHomePathInStore, null, namespaceService, false); NodeRef companyHomeNodeRef = nodeRefs.get(0); nodeRefs = searchService.selectNodes(storeRootNodeRef, companyHomePathInStore + "/" + NamespaceService.CONTENT_MODEL_PREFIX + ":" + IMAP_FOLDER_NAME, null, namespaceService, false); if (nodeRefs != null && nodeRefs.size() > 0) { fileFolderService.delete(nodeRefs.get(0)); } ChildApplicationContextFactory imap = (ChildApplicationContextFactory) ctx.getBean("imap"); ApplicationContext imapCtx = imap.getApplicationContext(); ImapServiceImpl imapServiceImpl = (ImapServiceImpl) imapCtx.getBean("imapService"); imapServer = (AlfrescoImapServer) imapCtx.getBean("imapServer"); if (!imapServer.isImapServerEnabled()) { imapServer.setImapServerEnabled(true); imapServer.setHost(HOST); imapServer.setPort(PORT); imapServer.startup(); } // Creating IMAP test folder for IMAP root LinkedList<String> folders = new LinkedList<String>(); folders.add(IMAP_FOLDER_NAME); FileFolderUtil.makeFolders(fileFolderService, companyHomeNodeRef, folders, ContentModel.TYPE_FOLDER); // Setting IMAP root RepositoryFolderConfigBean imapHome = new RepositoryFolderConfigBean(); imapHome.setStore(storePath); imapHome.setRootPath(companyHomePathInStore); imapHome.setFolderPath(NamespaceService.CONTENT_MODEL_PREFIX + ":" + IMAP_FOLDER_NAME); imapServiceImpl.setImapHome(imapHome); // Starting IMAP imapServiceImpl.startupInTxn(true); nodeRefs = searchService.selectNodes(storeRootNodeRef, companyHomePathInStore + "/" + NamespaceService.CONTENT_MODEL_PREFIX + ":" + IMAP_FOLDER_NAME, null, namespaceService, false); testImapFolderNodeRef = nodeRefs.get(0); /* * Importing test folders: Test folder contains: "___-___folder_a" "___-___folder_a" contains: "___-___folder_a_a", "___-___file_a", "Message_485.eml" (this is IMAP * Message) "___-___folder_a_a" contains: "____-____file_a_a" */ importInternal("imap/imapservice_test_folder_a.acp", testImapFolderNodeRef); txn.commit(); // Init mail client session Properties props = new Properties(); props.setProperty("mail.imap.partialfetch", "false"); this.session = Session.getDefaultInstance(props, null); // Get the store this.store = session.getStore(PROTOCOL); //this.store.connect(HOST, PORT, anotherUserName, anotherUserName); this.store.connect(imapServer.getHost(), imapServer.getPort(), anotherUserName, anotherUserName); // Get folder folder = (IMAPFolder) store.getFolder(TEST_FOLDER); folder.open(Folder.READ_ONLY); logger.debug("End SetUp"); }