List of usage examples for javax.mail PasswordAuthentication PasswordAuthentication
public PasswordAuthentication(String userName, String password)
From source file:com.twinsoft.convertigo.engine.admin.services.projects.Deploy.java
@Override protected void doUpload(HttpServletRequest request, Document document, FileItem item) throws Exception { if (!item.getName().endsWith(".car")) { ServiceUtils// w ww . ja v a2 s . c o m .addMessage(document, document.getDocumentElement(), "The deployment of the project " + item.getName() + " has failed. The archive file is not valid (.car required).", "error", false); } super.doUpload(request, document, item); // Depending on client browsers, according to the documentation, // item.getName() can either return a full path file name, or // simply a file name. String projectArchive = item.getName(); // Bugfix #1425 int i = projectArchive.lastIndexOf('/'); if (i == -1) { i = projectArchive.lastIndexOf('\\'); if (i != -1) { projectArchive = projectArchive.substring(i + 1); } } else { projectArchive = projectArchive.substring(i + 1); } String projectName = projectArchive.substring(0, projectArchive.indexOf(".car")); Engine.theApp.databaseObjectsManager.deployProject(getRepository() + projectArchive, true, bAssembleXsl); if (Boolean.parseBoolean( EnginePropertiesManager.getProperty(PropertyName.NOTIFICATIONS_NOTIFY_PROJECT_DEPLOYMENT))) { final String fUser = (String) request.getSession().getAttribute(SessionKey.ADMIN_USER.toString()); final String fProjectName = projectName; new Thread(new Runnable() { public void run() { try { Properties props = new Properties(); props.put("mail.smtp.host", EnginePropertiesManager.getProperty(PropertyName.NOTIFICATIONS_SMTP_HOST)); props.put("mail.smtp.socketFactory.port", EnginePropertiesManager.getProperty(PropertyName.NOTIFICATIONS_SMTP_PORT)); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); // Initializing Session mailSession = Session.getInstance(props, new Authenticator() { @Override public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication( EnginePropertiesManager.getProperty(PropertyName.NOTIFICATIONS_SMTP_USER), EnginePropertiesManager .getProperty(PropertyName.NOTIFICATIONS_SMTP_PASSWORD)); } }); MimeMessage message = new MimeMessage(mailSession); message.addRecipient(Message.RecipientType.TO, new InternetAddress( EnginePropertiesManager.getProperty(PropertyName.NOTIFICATIONS_TARGET_EMAIL))); message.setSubject("[trial] deployment of " + fProjectName + " by " + fUser); message.setText(message.getSubject() + "\n" + "http://trial.convertigo.net/cems/projects/" + fProjectName + "\n" + "https://trial.convertigo.net/cems/projects/" + fProjectName); Transport.send(message); } catch (MessagingException e1) { } } }).start(); } String message = "The project '" + projectName + "' has been successfully deployed."; Engine.logAdmin.info(message); ServiceUtils.addMessage(document, document.getDocumentElement(), message, "message", false); }
From source file:com.github.thorqin.toolkit.mail.MailService.java
private void sendMail(Mail mail) { long beginTime = System.currentTimeMillis(); Properties props = new Properties(); final Session session; props.put("mail.smtp.auth", String.valueOf(setting.auth)); // If want to display SMTP protocol detail then uncomment following statement // props.put("mail.debug", "true"); props.put("mail.smtp.host", setting.host); props.put("mail.smtp.port", setting.port); if (setting.secure.equals(SECURE_STARTTLS)) { props.put("mail.smtp.starttls.enable", "true"); } else if (setting.secure.equals(SECURE_SSL)) { props.put("mail.smtp.socketFactory.port", setting.port); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); }//w w w .j av a2 s .com if (!setting.auth) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(setting.user, setting.password); } }); if (setting.debug) session.setDebug(true); MimeMessage message = new MimeMessage(session); StringBuilder mailTo = new StringBuilder(); try { if (mail.from != null) message.setFrom(new InternetAddress(mail.from)); else if (setting.from != null) message.setFrom(new InternetAddress(setting.from)); if (mail.to != null) { for (String to : mail.to) { if (mailTo.length() > 0) mailTo.append(","); mailTo.append(to); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); } } if (mail.subject != null) message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?="); message.setSentDate(new Date()); BodyPart bodyPart = new MimeBodyPart(); if (mail.htmlBody != null) bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8"); else if (mail.textBody != null) bodyPart.setText(mail.textBody); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); if (mail.attachments != null) { for (String attachment : mail.attachments) { BodyPart attachedBody = new MimeBodyPart(); File attachedFile = new File(attachment); DataSource source = new FileDataSource(attachedFile); attachedBody.setDataHandler(new DataHandler(source)); attachedBody.setDisposition(MimeBodyPart.ATTACHMENT); String filename = attachedFile.getName(); attachedBody.setFileName( "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?="); multipart.addBodyPart(attachedBody); } } message.setContent(multipart); message.saveChanges(); Transport transport = session.getTransport("smtp"); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); if (setting.trace && tracer != null) { Tracer.Info info = new Tracer.Info(); info.catalog = "mail"; info.name = "send"; info.put("sender", StringUtils.join(message.getFrom())); info.put("recipients", mail.to); info.put("SMTPServer", setting.host); info.put("SMTPAccount", setting.user); info.put("subject", mail.subject); info.put("startTime", beginTime); info.put("runningTime", System.currentTimeMillis() - beginTime); tracer.trace(info); } } catch (Exception ex) { logger.log(Level.SEVERE, "Send mail failed!", ex); } }
From source file:com.cisco.iwe.services.util.EmailMonitor.java
/** * This method returns the corresponding JSON response.'Success = true' in case the Mail contents get stored in the database successfully. 'Success = false' in case of any errors **///from ww w . j a v a 2s. c o m public String monitorEmailAndLoadDB() { License license = new License(); license.setLicense(EmailParseConstants.ocrLicenseFile); Store emailStore = null; Folder folder = null; Properties props = new Properties(); logger.info("EmailMonitor monitorEmailAndLoadDB Enter (+)"); // Setting session and Store information // MailServerConnectivity - get the email credentials based on the environment String[] mailCredens = getEmailCredens(); final String username = mailCredens[0]; final String password = mailCredens[1]; logger.info("monitorEmailAndLoadDB : Email ID : " + username); try { logger.info("EmailMonitor.monitorEmailAndLoadDB get the mail server properties"); props.put(EmailParseConstants.emailAuthKey, "true"); props.put(EmailParseConstants.emailHostKey, prop.getProperty(EmailParseConstants.emailHost)); props.put(EmailParseConstants.emailPortKey, prop.getProperty(EmailParseConstants.emailPort)); props.put(EmailParseConstants.emailTlsKey, "true"); logger.info("EmailMonitor.monitorEmailAndLoadDB create the session object with mail server properties"); Session session = Session.getDefaultInstance(props, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); // Prod-MailServerConnectivity - create the POP3 store object and // connect with the pop server logger.info("monitorEmailAndLoadDB : create the POP3 store object"); emailStore = (Store) session.getStore(prop.getProperty(EmailParseConstants.emailType)); logger.info("monitorEmailAndLoadDB : Connecting to Store :" + emailStore.toString()); emailStore.connect(prop.getProperty(EmailParseConstants.emailHost), Integer.parseInt(prop.getProperty(EmailParseConstants.emailPort)), username, password); logger.info("monitorEmailAndLoadDB : Connection Status:" + emailStore.isConnected()); // create the folder object folder = emailStore.getFolder(prop.getProperty(EmailParseConstants.emailFolder)); // Check if Inbox exists if (!folder.exists()) { logger.error("monitorEmailAndLoadDB : No INBOX exists..."); System.exit(0); } // Open inbox and read messages logger.info("monitorEmailAndLoadDB : Connected to Folder"); folder.open(Folder.READ_WRITE); // retrieve the messages from the folder in an array and process it Message[] msgArr = folder.getMessages(); // Read each message and delete the same once data is stored in DB logger.info("monitorEmailAndLoadDB : Message length::::" + msgArr.length); SimpleDateFormat sdf2 = new SimpleDateFormat(EmailParseConstants.dateFormat); Date sent = null; String emailContent = null; String contentType = null; // for (int i = 0; i < msg.length; i++) { for (int i = msgArr.length - 1; i > msgArr.length - 2; i--) { Message message = msgArr[i]; if (!message.isSet(Flags.Flag.SEEN)) { try { sent = msgArr[i].getSentDate(); contentType = message.getContentType(); String fileType = null; byte[] byteArr = null; String validAttachments = EmailParseConstants.validAttachmentTypes; if (contentType.contains("multipart")) { Multipart multiPart = (Multipart) message.getContent(); int numberOfParts = multiPart.getCount(); for (int partCount = 0; partCount < numberOfParts; partCount++) { MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount); InputStream inStream = (InputStream) part.getInputStream(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[16384]; while ((nRead = inStream.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); byteArr = buffer.toByteArray(); if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) { fileType = part.getFileName().substring(part.getFileName().lastIndexOf("."), part.getFileName().length()); String fileDir = part.getFileName(); if (validAttachments.contains(fileType)) { part.saveFile(fileDir); saveAttachmentAndText(message.getFrom()[0].toString(), message.getSubject(), byteArr, emailContent.getBytes(), fileType, sent, fileType.equalsIgnoreCase(".PDF") ? scanPDF(fileDir) : scanImage(fileDir).toString()); deleteFile(fileDir); } else { sendNotification(); } } else { // this part may be the message content emailContent = part.getContent().toString(); } } } else if (contentType.contains("text/plain") || contentType.contains("text/html")) { Object content = message.getContent(); if (content != null) { emailContent = content.toString(); } } message.setFlag(Flags.Flag.DELETED, false); logger.info( "monitorEmailAndLoadDB : loadSuccess : Mail Parsed for : " + message.getSubject()); logger.info("monitorEmailAndLoadDB : loadSuccess : Created at : " + sdf2.format(sent)); logger.info("Message deleted"); } catch (IOException e) { logger.error("IO Exception in email monitoring: " + e); logger.error( "IO Exception in email monitoring message: " + Arrays.toString(e.getStackTrace())); } catch (SQLException sexp) { logger.error("SQLException Occurred GetSpogDetails-db2 :", sexp); buildErrorJson(ExceptionConstants.sqlErrCode, ExceptionConstants.sqlErrMsg); } catch (Exception e) { logger.error("Unknown Exception in email monitoring: " + e); logger.error("Unknown Exception in email monitoring message: " + Arrays.toString(e.getStackTrace())); } } } // Close folder and store folder.close(true); emailStore.close(); } catch (NoSuchProviderException e) { logger.error("monitorEmailAndLoadDB : NoSuchProviderException in email monitoring: " + e); logger.error("monitorEmailAndLoadDB : NoSuchProviderException in email monitoring message: " + Arrays.toString(e.getStackTrace())); } catch (MessagingException e) { logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: " + e); logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring message: " + Arrays.toString(e.getStackTrace())); } finally { if (folder != null && folder.isOpen()) { // Close folder and store try { folder.close(true); emailStore.close(); } catch (MessagingException e) { logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: " + e); logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: " + Arrays.toString(e.getStackTrace())); } } } logger.info("EmailMonitor monitorEmailAndLoadDB Exit (-)"); return buildSuccessJson().toString(); }
From source file:com.threepillar.labs.meeting.email.EmailInviteImpl.java
@Override public void sendInvite(final String subject, final String description, final Participant from, final List<Participant> attendees, final Date startDate, final Date endDate, final String location) throws Exception { this.properties.put("mail.smtp.socketFactory.port", properties.get("mail.smtp.port")); this.properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); this.properties.put("mail.smtp.socketFactory.fallback", "false"); validate();//from w w w.j av a 2 s . co m LOG.info("Sending meeting invite"); LOG.debug("Mail Properties :: " + this.properties); Session session; if (password != null) { session = Session.getInstance(this.properties, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); } else { session = Session.getInstance(this.properties); } ICal cal = new ICal(subject, description, from, attendees, startDate, endDate, location); cal.init(); StringBuffer sb = new StringBuffer(); sb.append(from.getEmail()); for (Participant bean : attendees) { if (sb.length() > 0) { sb.append(","); } sb.append(bean.getEmail()); } MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from.getEmail())); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(sb.toString())); message.setSubject(subject); Multipart multipart = new MimeMultipart(); MimeBodyPart iCal = new MimeBodyPart(); iCal.setDataHandler(new DataHandler(new ByteArrayDataSource(new ByteArrayInputStream(cal.toByteArray()), "text/calendar;method=REQUEST;charset=\"UTF-8\""))); LOG.debug("Calender Request :: \n" + cal.toString()); multipart.addBodyPart(iCal); message.setContent(multipart); Transport.send(message); }
From source file:org.artifactory.mail.MailServiceImpl.java
/** * Send an e-mail message//from w w w.j a v a 2 s .c om * * @param recipients Recipients of the message that will be sent * @param subject The subject of the message * @param body The body of the message * @param config A mail server configuration to use * @throws Exception */ @Override public void sendMail(String[] recipients, String subject, String body, final MailServerConfiguration config) throws EmailException { verifyParameters(recipients, config); if (!config.isEnabled()) { log.debug("Ignoring requested mail delivery. The given configuration is disabled."); return; } boolean debugEnabled = log.isDebugEnabled(); Properties properties = new Properties(); properties.put("mail.smtp.host", config.getHost()); properties.put("mail.smtp.port", Integer.toString(config.getPort())); properties.put("mail.smtp.quitwait", "false"); //Default protocol String protocol = "smtp"; //Enable TLS if set if (config.isUseTls()) { properties.put("mail.smtp.starttls.enable", "true"); } //Enable SSL if set boolean useSsl = config.isUseSsl(); if (useSsl) { properties.put("mail.smtp.socketFactory.port", Integer.toString(config.getPort())); properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.put("mail.smtp.socketFactory.fallback", "false"); //Requires special protocol protocol = "smtps"; } //Set debug property if enabled by the logger properties.put("mail.debug", debugEnabled); Authenticator authenticator = null; if (!StringUtils.isEmpty(config.getUsername())) { properties.put("mail.smtp.auth", "true"); authenticator = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(config.getUsername(), config.getPassword()); } }; } Session session = Session.getInstance(properties, authenticator); Message message = new MimeMessage(session); String subjectPrefix = config.getSubjectPrefix(); String fullSubject = (!StringUtils.isEmpty(subjectPrefix)) ? (subjectPrefix + " " + subject) : subject; try { message.setSubject(fullSubject); if (!StringUtils.isEmpty(config.getFrom())) { InternetAddress addressFrom = new InternetAddress(config.getFrom()); message.setFrom(addressFrom); } InternetAddress[] addressTo = new InternetAddress[recipients.length]; for (int i = 0; i < recipients.length; i++) { addressTo[i] = new InternetAddress(recipients[i]); } message.addRecipients(Message.RecipientType.TO, addressTo); //Create multi-part message in case we want to add html support Multipart multipart = new MimeMultipart("related"); BodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(body, "text/html"); multipart.addBodyPart(htmlPart); message.setContent(multipart); //Set debug property if enabled by the logger session.setDebug(debugEnabled); //Connect and send Transport transport = session.getTransport(protocol); if (useSsl) { transport.connect(config.getHost(), config.getPort(), config.getUsername(), config.getPassword()); } else { transport.connect(); } transport.sendMessage(message, message.getAllRecipients()); transport.close(); } catch (MessagingException e) { String em = e.getMessage(); throw new EmailException( "An error has occurred while sending an e-mail" + (em != null ? ": " + em.trim() : "") + ".\n", e); } }
From source file:com.iorga.webappwatcher.watcher.RetentionLogWritingWatcher.java
protected void sendMailForEvent(final RetentionLogWritingEvent event) { log.info("Trying to send a mail for event " + event); new Thread(new Runnable() { @Override//ww w . jav a 2 s . c om public void run() { if (StringUtils.isEmpty(getMailSmtpHost()) || getMailSmtpPort() == null) { // no configuration defined, exiting log.error("Either SMTP host or port was not defined, not sending that mail"); return; } // example from http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/ final Properties props = new Properties(); props.put("mail.smtp.host", getMailSmtpHost()); props.put("mail.smtp.port", getMailSmtpPort()); final Boolean auth = getMailSmtpAuth(); Authenticator authenticator = null; if (BooleanUtils.isTrue(auth)) { props.put("mail.smtp.auth", "true"); authenticator = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(getMailSmtpUsername(), getMailSmtpPassword()); } }; } if (StringUtils.equalsIgnoreCase(getMailSmtpSecurityType(), "SSL")) { props.put("mail.smtp.socketFactory.port", getMailSmtpPort()); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); } else if (StringUtils.equalsIgnoreCase(getMailSmtpSecurityType(), "TLS")) { props.put("mail.smtp.starttls.enable", "true"); } final Session session = Session.getDefaultInstance(props, authenticator); try { final MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(getMailFrom())); message.setRecipients(RecipientType.TO, InternetAddress.parse(getMailTo())); message.setSubject(event.getReason()); if (event.getContext() != null) { final StringBuilder contextText = new StringBuilder(); for (final Entry<String, Object> contextEntry : event.getContext().entrySet()) { contextText.append(contextEntry.getKey()).append(" = ").append(contextEntry.getValue()) .append("\n"); } message.setText(contextText.toString()); } else { message.setText("Context null"); } Transport.send(message); } catch (final MessagingException e) { log.error("Problem while sending a mail", e); } } }, RetentionLogWritingWatcher.class.getSimpleName() + ":sendMailer").start(); // send mail in an async way }
From source file:org.apache.juddi.subscription.notify.USERFRIENDLYSMTPNotifier.java
public static void notifySubscriptionDeleted(TemporaryMailContainer container) { try {/*from w w w . ja v a 2 s. com*/ Publisher publisher = container.getPublisher(); Publisher deletedBy = container.getDeletedBy(); Subscription obj = container.getObj(); String emailaddress = publisher.getEmailAddress(); if (emailaddress == null || emailaddress.trim().equals("")) return; Properties properties = new Properties(); Session session = null; String mailPrefix = AppConfig.getConfiguration().getString(Property.JUDDI_EMAIL_PREFIX, Property.DEFAULT_JUDDI_EMAIL_PREFIX); if (!mailPrefix.endsWith(".")) { mailPrefix = mailPrefix + "."; } for (String key : mailProps) { if (AppConfig.getConfiguration().containsKey(mailPrefix + key)) { properties.put(key, AppConfig.getConfiguration().getProperty(mailPrefix + key)); } else if (System.getProperty(mailPrefix + key) != null) { properties.put(key, System.getProperty(mailPrefix + key)); } } boolean auth = (properties.getProperty("mail.smtp.auth", "false")).equalsIgnoreCase("true"); if (auth) { final String username = properties.getProperty("mail.smtp.user"); String pwd = properties.getProperty("mail.smtp.password"); //decrypt if possible if (properties.getProperty("mail.smtp.password" + Property.ENCRYPTED_ATTRIBUTE, "false") .equalsIgnoreCase("true")) { try { pwd = CryptorFactory.getCryptor().decrypt(pwd); } catch (NoSuchPaddingException ex) { log.error("Unable to decrypt settings", ex); } catch (NoSuchAlgorithmException ex) { log.error("Unable to decrypt settings", ex); } catch (InvalidAlgorithmParameterException ex) { log.error("Unable to decrypt settings", ex); } catch (InvalidKeyException ex) { log.error("Unable to decrypt settings", ex); } catch (IllegalBlockSizeException ex) { log.error("Unable to decrypt settings", ex); } catch (BadPaddingException ex) { log.error("Unable to decrypt settings", ex); } } final String password = pwd; log.debug("SMTP username = " + username + " from address = " + emailaddress); Properties eMailProperties = properties; eMailProperties.remove("mail.smtp.user"); eMailProperties.remove("mail.smtp.password"); session = Session.getInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); } else { Properties eMailProperties = properties; eMailProperties.remove("mail.smtp.user"); eMailProperties.remove("mail.smtp.password"); session = Session.getInstance(eMailProperties); } MimeMessage message = new MimeMessage(session); InternetAddress address = new InternetAddress(emailaddress); Address[] to = { address }; message.setRecipients(RecipientType.TO, to); message.setFrom(new InternetAddress(properties.getProperty("mail.smtp.from", "jUDDI"))); //Hello %s,<br><br>Your subscription UDDI subscription was deleted. Attached is what the subscription was. It was deleted by %s, %s at %s. This node is %s //maybe nice to use a template rather then sending raw xml. org.uddi.sub_v3.Subscription api = new org.uddi.sub_v3.Subscription(); MappingModelToApi.mapSubscription(obj, api); String subscriptionResultXML = JAXBMarshaller.marshallToString(api, JAXBMarshaller.PACKAGE_SUBSCR_RES); Multipart mp = new MimeMultipart(); MimeBodyPart content = new MimeBodyPart(); String msg_content = ResourceConfig.getGlobalMessage("notifications.smtp.subscriptionDeleted"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd kk:mm:ssZ"); //Hello %s, %s<br><br>Your subscription UDDI subscription was deleted. Attached is what the subscription was. It was deleted by %s, %s at %s. This node is %s. msg_content = String.format(msg_content, StringEscapeUtils.escapeHtml(publisher.getPublisherName()), StringEscapeUtils.escapeHtml(publisher.getAuthorizedName()), StringEscapeUtils.escapeHtml(deletedBy.getPublisherName()), StringEscapeUtils.escapeHtml(deletedBy.getAuthorizedName()), StringEscapeUtils.escapeHtml(sdf.format(new Date())), StringEscapeUtils.escapeHtml( AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID, "(unknown node id!)")), AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL, "(unknown url)"), AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL_SECURE, "(unknown url)")); content.setContent(msg_content, "text/html; charset=UTF-8;"); mp.addBodyPart(content); MimeBodyPart attachment = new MimeBodyPart(); attachment.setContent(subscriptionResultXML, "text/xml; charset=UTF-8;"); attachment.setFileName("uddiNotification.xml"); mp.addBodyPart(attachment); message.setContent(mp); message.setSubject(ResourceConfig.getGlobalMessage("notifications.smtp.userfriendly.subject") + " " + StringEscapeUtils.escapeHtml(obj.getSubscriptionKey())); Transport.send(message); } catch (Throwable t) { log.warn("Error sending email!" + t.getMessage()); log.debug("Error sending email!" + t.getMessage(), t); } }
From source file:org.tomitribe.tribestream.registryng.service.monitoring.MailAlerter.java
@PostConstruct private void init() { active = active && to != null; if (!active) { return;/*from w w w . jav a2 s . c o m*/ } try { hostname = InetAddress.getLocalHost().getHostName(); } catch (final UnknownHostException e) { hostname = "unknown"; } final Properties properties = new Properties(); properties.setProperty("mail.transport.protocol", transport); properties.setProperty("mail." + transport + ".host", host); properties.setProperty("mail." + transport + ".port", Integer.toString(port)); if (tls) { properties.setProperty("mail." + transport + ".starttls.enable", "true"); } if (user != null) { properties.setProperty("mail." + transport + ".user", user); } if (password != null) { properties.setProperty("password", password); } if (auth || password != null) { properties.setProperty("mail." + transport + ".auth", "true"); } if (timeout > 0) { properties.setProperty("mail." + transport + ".timeout", Integer.toString(timeout)); } if (password != null) { final PasswordAuthentication pa = new PasswordAuthentication(user, password); session = Session.getInstance(properties, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return pa; } }); } else { session = Session.getInstance(properties); } }
From source file:org.apache.synapse.transport.mail.MailTransportSender.java
/** * Initialize the Mail sender and be ready to send messages * @param cfgCtx the axis2 configuration context * @param transportOut the transport-out description * @throws org.apache.axis2.AxisFault on error *//* w w w . j a v a 2 s .c o m*/ public void init(ConfigurationContext cfgCtx, TransportOutDescription transportOut) throws AxisFault { setTransportName(MailConstants.TRANSPORT_NAME); super.init(cfgCtx, transportOut); // initialize SMTP session Properties props = new Properties(); List<Parameter> params = transportOut.getParameters(); for (Parameter p : params) { props.put(p.getName(), p.getValue()); } if (props.containsKey(MailConstants.MAIL_SMTP_FROM)) { try { smtpFromAddress = new InternetAddress((String) props.get(MailConstants.MAIL_SMTP_FROM)); } catch (AddressException e) { handleException("Invalid default 'From' address : " + props.get(MailConstants.MAIL_SMTP_FROM), e); } } if (props.containsKey(MailConstants.MAIL_SMTP_BCC)) { try { smtpBccAddresses = InternetAddress.parse((String) props.get(MailConstants.MAIL_SMTP_BCC)); } catch (AddressException e) { handleException("Invalid default 'Bcc' address : " + props.get(MailConstants.MAIL_SMTP_BCC), e); } } if (props.containsKey(MailConstants.TRANSPORT_MAIL_FORMAT)) { defaultMailFormat = (String) props.get(MailConstants.TRANSPORT_MAIL_FORMAT); } smtpUsername = (String) props.get(MailConstants.MAIL_SMTP_USERNAME); smtpPassword = (String) props.get(MailConstants.MAIL_SMTP_PASSWORD); if (smtpUsername != null && smtpPassword != null) { session = Session.getInstance(props, new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(smtpUsername, smtpPassword); } }); } else { session = Session.getInstance(props, null); } // add handlers for main MIME types MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap(); mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html"); mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml"); mc.addMailcap("application/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml"); mc.addMailcap("application/soap+xml;; x-java-content-handler=com.sun.mail.handlers.text_xml"); mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain"); mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed"); mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822"); CommandMap.setDefaultCommandMap(mc); session.setDebug(log.isTraceEnabled()); }
From source file:com.mycompany.craftdemo.utility.java
public static void send(long phno, double price, double profit, String domain, String company) { HashMap<String, String> domainMap = new HashMap<>(); domainMap.put("TMobile", "tmomail.net "); domainMap.put("ATT", "txt.att.net"); domainMap.put("Sprint", "messaging.sprintpcs.com"); domainMap.put("Verizon", "vtext.com"); String to = phno + "@" + domainMap.get(domain); //change accordingly // Sender's email ID needs to be mentioned String from = "uni5prince@gmail.com"; //change accordingly final String username = "uni5prince"; //change accordingly final String password = "savageph8893"; //change accordingly // Assuming you are sending email through relay.jangosmtp.net String host = "smtp.gmail.com"; 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", "587"); // Get the Session object. Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); }//from w w w .j a v a 2 s . c om }); 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("Prices have gone up!!"); // Now set the actual message message.setText("Hello Jane, Stock prices for " + company + " has reached to $" + price + " with profit of $" + profit); // Send message Transport.send(message); System.out.println("Sent message successfully...."); } catch (MessagingException e) { throw new RuntimeException(e); } }