List of usage examples for javax.mail Transport send
public static void send(Message msg) throws MessagingException
From source file:org.orbeon.oxf.processor.EmailProcessor.java
public void start(PipelineContext pipelineContext) { try {//from w ww . j a va2 s . c o m final Document dataDocument = readInputAsDOM4J(pipelineContext, INPUT_DATA); final Element messageElement = dataDocument.getRootElement(); // Get system id (will likely be null if document is generated dynamically) final LocationData locationData = (LocationData) messageElement.getData(); final String dataInputSystemId = locationData.getSystemID(); // Set SMTP host final Properties properties = new Properties(); final String testSmtpHostProperty = getPropertySet().getString(EMAIL_TEST_SMTP_HOST); if (testSmtpHostProperty != null) { // Test SMTP Host from properties overrides the local configuration properties.setProperty("mail.smtp.host", testSmtpHostProperty); } else { // Try regular config parameter and property String host = messageElement.element("smtp-host").getTextTrim(); if (host != null && !host.equals("")) { // Precedence goes to the local config parameter properties.setProperty("mail.smtp.host", host); } else { // Otherwise try to use a property host = getPropertySet().getString(EMAIL_SMTP_HOST); if (host == null) host = getPropertySet().getString(EMAIL_HOST_DEPRECATED); if (host == null) throw new OXFException("Could not find SMTP host in configuration or in properties"); properties.setProperty("mail.smtp.host", host); } } // Create session final Session session; { // Get credentials final String usernameTrimmed; final String passwordTrimmed; { final Element credentials = messageElement.element("credentials"); if (credentials != null) { final Element usernameElement = credentials.element("username"); final Element passwordElement = credentials.element("password"); usernameTrimmed = (usernameElement != null) ? usernameElement.getStringValue().trim() : null; passwordTrimmed = (passwordElement != null) ? passwordElement.getStringValue().trim() : ""; } else { usernameTrimmed = null; passwordTrimmed = null; } } // Check if credentials are supplied if (StringUtils.isNotEmpty(usernameTrimmed)) { // NOTE: A blank username doesn't trigger authentication if (logger.isInfoEnabled()) logger.info("Authentication"); // Set the auth property to true properties.setProperty("mail.smtp.auth", "true"); if (logger.isInfoEnabled()) logger.info("Username: " + usernameTrimmed); // Create an authenticator final Authenticator authenticator = new SMTPAuthenticator(usernameTrimmed, passwordTrimmed); // Create session with authenticator session = Session.getInstance(properties, authenticator); } else { if (logger.isInfoEnabled()) logger.info("No Authentication"); session = Session.getInstance(properties); } } // Create message final Message message = new MimeMessage(session); // Set From message.addFrom(createAddresses(messageElement.element("from"))); // Set To String testToProperty = getPropertySet().getString(EMAIL_TEST_TO); if (testToProperty == null) testToProperty = getPropertySet().getString(EMAIL_FORCE_TO_DEPRECATED); if (testToProperty != null) { // Test To from properties overrides local configuration message.addRecipient(Message.RecipientType.TO, new InternetAddress(testToProperty)); } else { // Regular list of To elements for (final Element toElement : Dom4jUtils.elements(messageElement, "to")) { final InternetAddress[] addresses = createAddresses(toElement); message.addRecipients(Message.RecipientType.TO, addresses); } } // Set Cc for (final Element ccElement : Dom4jUtils.elements(messageElement, "cc")) { final InternetAddress[] addresses = createAddresses(ccElement); message.addRecipients(Message.RecipientType.CC, addresses); } // Set Bcc for (final Element bccElement : Dom4jUtils.elements(messageElement, "bcc")) { final InternetAddress[] addresses = createAddresses(bccElement); message.addRecipients(Message.RecipientType.BCC, addresses); } // Set headers if any for (final Element headerElement : Dom4jUtils.elements(messageElement, "header")) { final String headerName = headerElement.element("name").getTextTrim(); final String headerValue = headerElement.element("value").getTextTrim(); // NOTE: Use encodeText() in case there are non-ASCII characters message.addHeader(headerName, MimeUtility.encodeText(headerValue, DEFAULT_CHARACTER_ENCODING, null)); } // Set the email subject // The JavaMail spec is badly written and is not clear about whether this needs to be done here. But it // seems to use the platform's default charset, which we don't want to deal with. So we preemptively encode. // The result is pure ASCII so that setSubject() will not attempt to re-encode it. message.setSubject(MimeUtility.encodeText(messageElement.element("subject").getStringValue(), DEFAULT_CHARACTER_ENCODING, null)); // Handle body final Element textElement = messageElement.element("text"); final Element bodyElement = messageElement.element("body"); if (textElement != null) { // Old deprecated mechanism (simple text body) message.setText(textElement.getStringValue()); } else if (bodyElement != null) { // New mechanism with body and parts handleBody(pipelineContext, dataInputSystemId, message, bodyElement); } else { throw new OXFException("Main text or body element not found");// TODO: location info } // Send message final Transport transport = session.getTransport("smtp"); Transport.send(message); transport.close(); } catch (Exception e) { throw new OXFException(e); } }
From source file:net.tradelib.apps.StrategyBacktest.java
public static void run(Strategy strategy) throws Exception { // Setup the logging System.setProperty("java.util.logging.SimpleFormatter.format", "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS: %4$s: %5$s%n%6$s%n"); LogManager.getLogManager().reset(); Logger rootLogger = Logger.getLogger(""); if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("file.log", "true"))) { FileHandler logHandler = new FileHandler("diag.out", 8 * 1024 * 1024, 2, true); logHandler.setFormatter(new SimpleFormatter()); logHandler.setLevel(Level.FINEST); rootLogger.addHandler(logHandler); }//from w w w.j a va 2 s . c o m if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("console.log", "true"))) { ConsoleHandler consoleHandler = new ConsoleHandler(); consoleHandler.setFormatter(new SimpleFormatter()); consoleHandler.setLevel(Level.INFO); rootLogger.addHandler(consoleHandler); } rootLogger.setLevel(Level.INFO); // Setup Hibernate // Configuration configuration = new Configuration(); // StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()); // SessionFactory factory = configuration.buildSessionFactory(builder.build()); Context context = new Context(); context.dbUrl = BacktestCfg.instance().getProperty("db.url"); HistoricalDataFeed hdf = new SQLDataFeed(context); hdf.configure(BacktestCfg.instance().getProperty("datafeed.config", "config/datafeed.properties")); context.historicalDataFeed = hdf; HistoricalReplay hr = new HistoricalReplay(context); context.broker = hr; strategy.initialize(context); strategy.cleanupDb(); long start = System.nanoTime(); strategy.start(); long elapsedTime = System.nanoTime() - start; System.out.println("backtest took " + String.format("%.2f secs", (double) elapsedTime / 1e9)); start = System.nanoTime(); strategy.updateEndEquity(); strategy.writeExecutionsAndTrades(); strategy.writeEquity(); elapsedTime = System.nanoTime() - start; System.out .println("writing to the database took " + String.format("%.2f secs", (double) elapsedTime / 1e9)); System.out.println(); // Write the strategy totals to the database strategy.totalTradeStats(); // Write the strategy report to the database and obtain the JSON // for writing it to the console. JsonObject report = strategy.writeStrategyReport(); JsonArray asa = report.getAsJsonArray("annual_stats"); String csvPath = BacktestCfg.instance().getProperty("positions.csv.prefix"); if (!Strings.isNullOrEmpty(csvPath)) { csvPath += "-" + strategy.getLastTimestamp().toLocalDate().format(DateTimeFormatter.BASIC_ISO_DATE) + ".csv"; } String ordersCsvPath = BacktestCfg.instance().getProperty("orders.csv.suffix"); if (!Strings.isNullOrEmpty(ordersCsvPath)) { ordersCsvPath = strategy.getLastTimestamp().toLocalDate().format(DateTimeFormatter.BASIC_ISO_DATE) + "-" + strategy.getName() + ordersCsvPath; } String actionsPath = BacktestCfg.instance().getProperty("actions.file.suffix"); if (!Strings.isNullOrEmpty(actionsPath)) { actionsPath = strategy.getLastTimestamp().toLocalDate().format(DateTimeFormatter.BASIC_ISO_DATE) + "-" + strategy.getName() + actionsPath; } // If emails are being send out String signalText = StrategyText.build(context.dbUrl, strategy.getName(), strategy.getLastTimestamp().toLocalDate(), " ", csvPath, '|'); System.out.println(signalText); System.out.println(); if (!Strings.isNullOrEmpty(ordersCsvPath)) { StrategyText.buildOrdersCsv(context.dbUrl, strategy.getName(), strategy.getLastTimestamp().toLocalDate(), ordersCsvPath); } File actionsFile = Strings.isNullOrEmpty(actionsPath) ? null : new File(actionsPath); if (actionsFile != null) { FileUtils.writeStringToFile(actionsFile, signalText + System.getProperty("line.separator") + System.getProperty("line.separator")); } String message = ""; if (asa.size() > 0) { // Sort the array TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>(); for (int ii = 0; ii < asa.size(); ++ii) { int year = asa.get(ii).getAsJsonObject().get("year").getAsInt(); map.put(year, ii); } for (int id : map.values()) { JsonObject jo = asa.get(id).getAsJsonObject(); String yearStr = String.valueOf(jo.get("year").getAsInt()); String pnlStr = String.format("$%,d", jo.get("pnl").getAsInt()); String pnlPctStr = String.format("%.2f%%", jo.get("pnl_pct").getAsDouble()); String endEqStr = String.format("$%,d", jo.get("end_equity").getAsInt()); String ddStr = String.format("$%,d", jo.get("maxdd").getAsInt()); String ddPctStr = String.format("%.2f%%", jo.get("maxdd_pct").getAsDouble()); String str = yearStr + " PnL: " + pnlStr + ", PnL Pct: " + pnlPctStr + ", End Equity: " + endEqStr + ", MaxDD: " + ddStr + ", Pct MaxDD: " + ddPctStr; message += str + "\n"; } String pnlStr = String.format("$%,d", report.get("pnl").getAsInt()); String pnlPctStr = String.format("%.2f%%", report.get("pnl_pct").getAsDouble()); String ddStr = String.format("$%,d", report.get("avgdd").getAsInt()); String ddPctStr = String.format("%.2f%%", report.get("avgdd_pct").getAsDouble()); String gainToPainStr = String.format("%.4f", report.get("gain_to_pain").getAsDouble()); String str = "\nAvg PnL: " + pnlStr + ", Pct Avg PnL: " + pnlPctStr + ", Avg DD: " + ddStr + ", Pct Avg DD: " + ddPctStr + ", Gain to Pain: " + gainToPainStr; message += str + "\n"; } else { message += "\n"; } // Global statistics JsonObject jo = report.getAsJsonObject("total_peak"); String dateStr = jo.get("date").getAsString(); int maxEndEq = jo.get("equity").getAsInt(); jo = report.getAsJsonObject("total_maxdd"); double cash = jo.get("cash").getAsDouble(); double pct = jo.get("pct").getAsDouble(); message += "\n" + "Total equity peak [" + dateStr + "]: " + String.format("$%,d", maxEndEq) + "\n" + String.format("Current Drawdown: $%,d [%.2f%%]", Math.round(cash), pct) + "\n"; if (report.has("latest_peak") && report.has("latest_maxdd")) { jo = report.getAsJsonObject("latest_peak"); LocalDate ld = LocalDate.parse(jo.get("date").getAsString(), DateTimeFormatter.ISO_DATE); maxEndEq = jo.get("equity").getAsInt(); jo = report.getAsJsonObject("latest_maxdd"); cash = jo.get("cash").getAsDouble(); pct = jo.get("pct").getAsDouble(); message += "\n" + Integer.toString(ld.getYear()) + " equity peak [" + ld.format(DateTimeFormatter.ISO_DATE) + "]: " + String.format("$%,d", maxEndEq) + "\n" + String.format("Current Drawdown: $%,d [%.2f%%]", Math.round(cash), pct) + "\n"; } message += "\n" + "Avg Trade PnL: " + String.format("$%,d", Math.round(report.get("avg_trade_pnl").getAsDouble())) + ", Max DD: " + String.format("$%,d", Math.round(report.get("maxdd").getAsDouble())) + ", Max DD Pct: " + String.format("%.2f%%", report.get("maxdd_pct").getAsDouble()) + ", Num Trades: " + Integer.toString(report.get("num_trades").getAsInt()); System.out.println(message); if (actionsFile != null) { FileUtils.writeStringToFile(actionsFile, message + System.getProperty("line.separator"), true); } if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("email.enabled", "false"))) { Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.sendgrid.net"); props.put("mail.smtp.port", "587"); String user = BacktestCfg.instance().getProperty("email.user"); String pass = BacktestCfg.instance().getProperty("email.pass"); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(user, pass); } }); MimeMessage msg = new MimeMessage(session); try { msg.setFrom(new InternetAddress(BacktestCfg.instance().getProperty("email.from"))); msg.addRecipients(RecipientType.TO, BacktestCfg.instance().getProperty("email.recipients")); msg.setSubject(strategy.getName() + " Report [" + strategy.getLastTimestamp().format(DateTimeFormatter.ISO_LOCAL_DATE) + "]"); msg.setText("Positions & Signals\n" + signalText + "\n\nStatistics\n" + message); Transport.send(msg); } catch (Exception ee) { Logger.getLogger("").warning(ee.getMessage()); } } if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("sftp.enabled", "false"))) { HashMap<String, String> fileMap = new HashMap<String, String>(); if (!Strings.isNullOrEmpty(actionsPath)) fileMap.put(actionsPath, actionsPath); if (!Strings.isNullOrEmpty(ordersCsvPath)) fileMap.put(ordersCsvPath, ordersCsvPath); String user = BacktestCfg.instance().getProperty("sftp.user"); String pass = BacktestCfg.instance().getProperty("sftp.pass"); String host = BacktestCfg.instance().getProperty("sftp.host"); SftpUploader sftp = new SftpUploader(host, user, pass); sftp.upload(fileMap); } }
From source file:com.email.SendEmail.java
/** * Sends a single email and uses account based off of the section that the * email comes from after email is sent the attachments are gathered * together and collated into a single PDF file and a history entry is * created based off of that entry//from w w w . j a v a 2 s . c om * * @param eml EmailOutModel */ public static void sendEmails(EmailOutModel eml) { SystemEmailModel account = null; String section = eml.getSection(); if (eml.getSection().equalsIgnoreCase("Hearings") && (eml.getCaseType().equalsIgnoreCase("MED") || eml.getCaseType().equalsIgnoreCase("REP") || eml.getCaseType().equalsIgnoreCase("ULP"))) { section = eml.getCaseType(); } //Get Account for (SystemEmailModel acc : Global.getSystemEmailParams()) { if (acc.getSection().equals(section)) { account = acc; break; } } //Account Exists? if (account != null) { //Case Location String casePath = (eml.getCaseType().equals("CSC") || eml.getCaseType().equals("ORG")) ? FileService.getCaseFolderORGCSCLocation(eml) : FileService.getCaseFolderLocation(eml); //Attachment List boolean allFilesExists = true; List<EmailOutAttachmentModel> attachmentList = EmailOutAttachment.getAttachmentsByEmail(eml.getId()); for (EmailOutAttachmentModel attach : attachmentList) { File attachment = new File(casePath + attach.getFileName()); boolean exists = attachment.exists(); if (exists == false) { allFilesExists = false; SECExceptionsModel item = new SECExceptionsModel(); item.setClassName("SendEmail"); item.setMethodName("sendEmails"); item.setExceptionType("FileMissing"); item.setExceptionDescription("Can't Send Email, File Missing for EmailID: " + eml.getId() + System.lineSeparator() + "EmailSubject: " + eml.getSubject() + System.lineSeparator() + "File: " + attachment); ExceptionHandler.HandleNoException(item); break; } else { if ("docx".equalsIgnoreCase(FilenameUtils.getExtension(attach.getFileName())) || "doc".equalsIgnoreCase(FilenameUtils.getExtension(attach.getFileName()))) { if (!attachment.renameTo(attachment)) { allFilesExists = false; SECExceptionsModel item = new SECExceptionsModel(); item.setClassName("SendEmail"); item.setMethodName("sendEmails"); item.setExceptionType("File In Use"); item.setExceptionDescription("Can't Send Email, File In Use for EmailID: " + eml.getId() + System.lineSeparator() + "EmailSubject: " + eml.getSubject() + System.lineSeparator() + "File: " + attachment); ExceptionHandler.HandleNoException(item); break; } } } } if (allFilesExists) { //Set up Initial Merge Utility PDFMergerUtility ut = new PDFMergerUtility(); //List ConversionPDFs To Delete Later List<String> tempPDFList = new ArrayList<>(); //create email message body Date emailSentTime = new Date(); String emailPDFname = EmailBodyToPDF.createEmailOutBody(eml, attachmentList, emailSentTime); //Add Email Body To PDF Merge try { ut.addSource(casePath + emailPDFname); tempPDFList.add(casePath + emailPDFname); } catch (FileNotFoundException ex) { ExceptionHandler.Handle(ex); } //Get parts String FromAddress = account.getEmailAddress(); String[] TOAddressess = ((eml.getTo() == null) ? "".split(";") : eml.getTo().split(";")); String[] CCAddressess = ((eml.getCc() == null) ? "".split(";") : eml.getCc().split(";")); String[] BCCAddressess = ((eml.getBcc() == null) ? "".split(";") : eml.getBcc().split(";")); String emailSubject = eml.getSubject(); String emailBody = eml.getBody(); //Set Email Parts Authenticator auth = EmailAuthenticator.setEmailAuthenticator(account); Properties properties = EmailProperties.setEmailOutProperties(account); Session session = Session.getInstance(properties, auth); MimeMessage smessage = new MimeMessage(session); Multipart multipart = new MimeMultipart(); //Add Parts to Email Message try { smessage.addFrom(new InternetAddress[] { new InternetAddress(FromAddress) }); for (String To : TOAddressess) { if (EmailValidator.getInstance().isValid(To)) { smessage.addRecipient(Message.RecipientType.TO, new InternetAddress(To)); } } for (String CC : CCAddressess) { if (EmailValidator.getInstance().isValid(CC)) { smessage.addRecipient(Message.RecipientType.CC, new InternetAddress(CC)); } } for (String BCC : BCCAddressess) { if (EmailValidator.getInstance().isValid(BCC)) { smessage.addRecipient(Message.RecipientType.BCC, new InternetAddress(BCC)); } } smessage.setSubject(emailSubject); MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(emailBody, "text/plain"); multipart.addBodyPart(messageBodyPart); //get attachments for (EmailOutAttachmentModel attachment : attachmentList) { String fileName = attachment.getFileName(); String extension = FilenameUtils.getExtension(fileName); //Convert attachments to PDF //If Image if (FileService.isImageFormat(fileName)) { fileName = ImageToPDF.createPDFFromImageNoDelete(casePath, fileName); //Add Attachment To PDF Merge try { ut.addSource(casePath + fileName); tempPDFList.add(casePath + fileName); } catch (FileNotFoundException ex) { ExceptionHandler.Handle(ex); } //If Word Doc } else if (extension.equals("docx") || extension.equals("doc")) { fileName = WordToPDF.createPDFNoDelete(casePath, fileName); //Add Attachment To PDF Merge try { ut.addSource(casePath + fileName); tempPDFList.add(casePath + fileName); } catch (FileNotFoundException ex) { ExceptionHandler.Handle(ex); } //If Text File } else if ("txt".equals(extension)) { fileName = TXTtoPDF.createPDFNoDelete(casePath, fileName); //Add Attachment To PDF Merge try { ut.addSource(casePath + fileName); tempPDFList.add(casePath + fileName); } catch (FileNotFoundException ex) { ExceptionHandler.Handle(ex); } //If PDF } else if (FilenameUtils.getExtension(fileName).equals("pdf")) { //Add Attachment To PDF Merge try { ut.addSource(casePath + fileName); } catch (FileNotFoundException ex) { ExceptionHandler.Handle(ex); } } DataSource source = new FileDataSource(casePath + fileName); messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(fileName); multipart.addBodyPart(messageBodyPart); } smessage.setContent(multipart); //Send Message if (Global.isOkToSendEmail()) { Transport.send(smessage); } else { Audit.addAuditEntry("Email Not Actually Sent: " + eml.getId() + " - " + emailSubject); } //DocumentFileName String savedDoc = (String.valueOf(new Date().getTime()) + "_" + eml.getSubject()) .replaceAll("[:\\\\/*?|<>]", "_") + ".pdf"; //Set Merge File Destination ut.setDestinationFileName(casePath + savedDoc); //Try to Merge try { ut.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly()); } catch (IOException ex) { ExceptionHandler.Handle(ex); } //Add emailBody Activity addEmailActivity(eml, savedDoc, emailSentTime); //Copy to related case folders if (section.equals("MED")) { List<RelatedCaseModel> relatedMedList = RelatedCase.getRelatedCases(eml); if (relatedMedList.size() > 0) { for (RelatedCaseModel related : relatedMedList) { //Copy finalized document to proper folder File srcFile = new File(casePath + savedDoc); File destPath = new File((section.equals("CSC") || section.equals("ORG")) ? FileService.getCaseFolderORGCSCLocation(related) : FileService.getCaseFolderLocationRelatedCase(related)); destPath.mkdirs(); try { FileUtils.copyFileToDirectory(srcFile, destPath); } catch (IOException ex) { Logger.getLogger(SendEmail.class.getName()).log(Level.SEVERE, null, ex); } //Add Related Case Activity Entry addEmailActivityRelatedCase(eml, related, savedDoc, emailSentTime); } } } else { //This is blanket and should grab all related cases. (UNTESTED outside of CMDS) List<EmailOutRelatedCaseModel> relatedList = EmailOutRelatedCase.getRelatedCases(eml); if (relatedList.size() > 0) { for (EmailOutRelatedCaseModel related : relatedList) { //Copy finalized document to proper folder File srcFile = new File(casePath + savedDoc); File destPath = new File((section.equals("CSC") || section.equals("ORG")) ? FileService.getCaseFolderORGCSCLocation(related) : FileService.getCaseFolderLocationEmailOutRelatedCase(related)); destPath.mkdirs(); try { FileUtils.copyFileToDirectory(srcFile, destPath); } catch (IOException ex) { Logger.getLogger(SendEmail.class.getName()).log(Level.SEVERE, null, ex); } //Add Related Case Activity Entry addEmailOutActivityRelatedCase(eml, related, savedDoc, emailSentTime); } } } //Clean SQL entries EmailOut.deleteEmailEntry(eml.getId()); EmailOutAttachment.deleteAttachmentsForEmail(eml.getId()); EmailOutRelatedCase.deleteEmailOutRelatedForEmail(eml.getId()); //Clean up temp PDFs for (String tempPDF : tempPDFList) { new File(tempPDF).delete(); } } catch (AddressException ex) { ExceptionHandler.Handle(ex); } catch (MessagingException ex) { ExceptionHandler.Handle(ex); } } } }
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);/* w w w .j a v a 2 s . c om*/ Transport.send(message); }
From source file:com.silverpeas.mailinglist.service.job.TestMessageChecker.java
@Test public void testProcessEmailHtmlText() throws MessagingException, IOException { MessageListener mockListener1 = mock(MessageListener.class); when(mockListener1.getComponentId()).thenReturn("componentId"); when(mockListener1.checkSender("bart.simpson@silverpeas.com")).thenReturn(Boolean.TRUE); MessageListener mockListener2 = mock(MessageListener.class); Map<String, MessageListener> listenersByEmail = new HashMap<String, MessageListener>(2); listenersByEmail.put("thesimpsons@silverpeas.com", mockListener1); listenersByEmail.put("theflanders@silverpeas.com", mockListener2); MimeMessage mail = new MimeMessage(messageChecker.getMailSession()); InternetAddress bart = new InternetAddress("bart.simpson@silverpeas.com"); InternetAddress theSimpsons = new InternetAddress("thesimpsons@silverpeas.com"); mail.addFrom(new InternetAddress[] { bart }); mail.addRecipient(RecipientType.TO, theSimpsons); mail.setSubject("Simple html Email test"); String html = loadHtml();//from w ww . j a v a2 s . co m mail.setText(html, "UTF-8", "html"); mail.setSentDate(new Date()); Date sentDate = new Date(mail.getSentDate().getTime()); Transport.send(mail); Map<MessageListener, MessageEvent> events = new HashMap<MessageListener, MessageEvent>(); messageChecker.processEmail(mail, events, listenersByEmail); assertNotNull(events); assertEquals(1, events.size()); assertNull(events.get(mockListener2)); MessageEvent event = events.get(mockListener1); assertNotNull(event); assertNotNull(event.getMessages()); assertEquals(1, event.getMessages().size()); Message message = event.getMessages().get(0); assertEquals("bart.simpson@silverpeas.com", message.getSender()); assertEquals("Simple html Email test", message.getTitle()); assertEquals(html, message.getBody()); assertNotNull(message.getSentDate()); assertEquals(sentDate.getTime(), message.getSentDate().getTime()); assertEquals(htmlEmailSummary, message.getSummary()); assertEquals(0, message.getAttachmentsSize()); assertEquals(0, message.getAttachments().size()); assertEquals("componentId", message.getComponentId()); assertEquals("text/html; charset=UTF-8", message.getContentType()); verify(mockListener1, atLeastOnce()).checkSender("bart.simpson@silverpeas.com"); }
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 {/*from ww w. j ava 2 s .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:edu.cornell.mannlib.vitro.webapp.controller.freemarker.ContactMailController.java
private void sendMessage(Session s, String webuseremail, String webusername, String[] recipients, String deliveryfrom, String msgText) throws AddressException, SendFailedException, MessagingException { // Construct the message MimeMessage msg = new MimeMessage(s); //System.out.println("trying to send message from servlet"); // Set the from address try {/*from w w w . j a va 2 s . co m*/ msg.setFrom(new InternetAddress(webuseremail, webusername)); } catch (UnsupportedEncodingException e) { log.error("Can't set message sender with personal name " + webusername + " due to UnsupportedEncodingException"); msg.setFrom(new InternetAddress(webuseremail)); } // Set the recipient address InternetAddress[] address = new InternetAddress[recipients.length]; for (int i = 0; i < recipients.length; i++) { address[i] = new InternetAddress(recipients[i]); } msg.setRecipients(Message.RecipientType.TO, address); // Set the subject and text msg.setSubject(deliveryfrom); // add the multipart to the message msg.setContent(msgText, "text/html"); // set the Date: header msg.setSentDate(new Date()); Transport.send(msg); // try to send the message via smtp - catch error exceptions }
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 ww w. j av a 2s.c om } // 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.fao.geonet.services.register.SelfRegister.java
/** * Send an email./*from ww w . j a v a2s.c om*/ * * @param host * @param port * @param subject * @param from * @param to * @param content * @return */ boolean sendMail(String host, int port, String subject, String from, String to, String content) { boolean isSendout = false; Properties props = new Properties(); props.put("mail.transport.protocol", PROTOCOL); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); props.put("mail.smtp.auth", "false"); Session mailSession = Session.getDefaultInstance(props); try { Message msg = new MimeMessage(mailSession); msg.setFrom(new InternetAddress(from)); msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); msg.setSentDate(new Date()); msg.setSubject(subject); // Add content message msg.setText(content); Transport.send(msg); isSendout = true; } catch (AddressException e) { isSendout = false; e.printStackTrace(); } catch (MessagingException e) { isSendout = false; e.printStackTrace(); } return isSendout; }
From source file:com.smartitengineering.emailq.service.impl.EmailServiceImpl.java
protected void sendEmail(Email email, List<Email> successfulEmails) { try {/* w w w .ja v a 2s . co m*/ if (logger.isDebugEnabled()) { logger.debug("Attempting to send " + email.getId() + " " + email.getSubject()); if (email.getTo() != null) { logger.debug("To: " + Arrays.toString(email.getTo().toArray())); } else { logger.debug("To is NULL"); } if (email.getTo() != null) { logger.debug("CC: " + Arrays.toString(email.getCc().toArray())); } else { logger.debug("CC is NULL"); } if (email.getTo() != null) { logger.debug("BCC: " + Arrays.toString(email.getBcc().toArray())); } else { logger.debug("BCC is NULL"); } if (email.getTo() != null) { logger.debug("FROM: " + email.getFrom()); } else { logger.debug("FROM is NULL"); } if (email.getAttachments() != null) { logger.debug("Attachments: " + Arrays.toString(email.getAttachments().toArray())); for (Attachments attachment : email.getAttachments()) { logger.debug("Attachment: " + attachment.getName()); } } else { logger.debug("No attachments"); } } //Send email if (StringUtils.isBlank(email.getSubject()) || StringUtils.isBlank(email.getFrom())) { logger.warn(new StringBuilder("Invalid email without either from or a subject, thus ignoring it ") .append(email.getId()).toString()); return; } MimeMessage message = new MimeMessage(session); message.setSubject(email.getSubject()); message.setFrom(new InternetAddress(email.getFrom())); addRecipients(message, Message.RecipientType.TO, email.getTo()); addRecipients(message, Message.RecipientType.CC, email.getCc()); addRecipients(message, Message.RecipientType.BCC, email.getBcc()); if (email.getMessage() != null && StringUtils.isNotBlank(email.getMessage().getMsgBody()) && email.getMessage().getMsgType().equals(MsgType.PLAIN) && (email.getAttachments() == null || email.getAttachments().isEmpty())) { message.setText(email.getMessage().getMsgBody()); } else { Multipart multipart = new MimeMultipart(); if (email.getMessage() != null && StringUtils.isNotBlank(email.getMessage().getMsgBody())) { MimeBodyPart bodyPart = new MimeBodyPart(); switch (email.getMessage().getMsgType()) { case HTML: bodyPart.setContent(email.getMessage().getMsgBody(), "html"); break; case PLAIN: default: bodyPart.setText(email.getMessage().getMsgBody()); } multipart.addBodyPart(bodyPart); } if (email.getAttachments() != null && !email.getAttachments().isEmpty()) { for (Attachments attachment : email.getAttachments()) { addAttachment(multipart, attachment); } } message.setContent(multipart); } Transport.send(message); if (logger.isDebugEnabled()) { logger.debug("Sent " + email.getId()); } //Update status email.setMailStatus(Email.MailStatus.SENT); successfulEmails.add(email); if (logger.isDebugEnabled()) { logger.debug("Set new mail status and add to successful queue " + email.getSubject()); } } catch (Exception ex) { logger.warn( new StringBuilder("Error sending email with subject ").append(email.getSubject()).toString(), ex); } }