List of usage examples for javax.mail.internet MimeMessage setFrom
public void setFrom(String address) throws MessagingException
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 www .ja v a 2s . c om*/ 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.hg.ecommerce.util.MailUtil.java
/** * This method is used to send a Message with a pre-defined * mime-type./* w ww. java 2 s . co m*/ * * @param from e-mail address of sender * @param to e-mail address(es) of recipients * @param subject subject of e-mail * @param content the body of the e-mail * @param mimeType type of message, i.e. text/plain or text/html * @throws MessagingException the exception to indicate failure */ public static void sendMessage(Session session, String from, String[] to, String[] cc, String[] bcc, String subject, String content, String mimeType) throws MessagingException { MimeMessage message = new MimeMessage(session); // n.b. any default from address is expected to be determined by caller. if (!StringUtils.isEmpty(from)) { InternetAddress sentFrom = new InternetAddress(from); message.setFrom(sentFrom); if (mLogger.isDebugEnabled()) { mLogger.debug("e-mail from: " + sentFrom); } } if (to != null) { InternetAddress[] sendTo = new InternetAddress[to.length]; for (int i = 0; i < to.length; i++) { sendTo[i] = new InternetAddress(to[i]); if (mLogger.isDebugEnabled()) { mLogger.debug("sending e-mail to: " + to[i]); } } message.setRecipients(Message.RecipientType.TO, sendTo); } if (cc != null) { InternetAddress[] copyTo = new InternetAddress[cc.length]; for (int i = 0; i < cc.length; i++) { copyTo[i] = new InternetAddress(cc[i]); if (mLogger.isDebugEnabled()) { mLogger.debug("copying e-mail to: " + cc[i]); } } message.setRecipients(Message.RecipientType.CC, copyTo); } if (bcc != null) { InternetAddress[] copyTo = new InternetAddress[bcc.length]; for (int i = 0; i < bcc.length; i++) { copyTo[i] = new InternetAddress(bcc[i]); if (mLogger.isDebugEnabled()) { mLogger.debug("blind copying e-mail to: " + bcc[i]); } } message.setRecipients(Message.RecipientType.BCC, copyTo); } message.setSubject((subject == null) ? "(no subject)" : subject, "UTF-8"); message.setContent(content, mimeType); message.setSentDate(new java.util.Date()); // First collect all the addresses together. Address[] remainingAddresses = message.getAllRecipients(); int nAddresses = remainingAddresses.length; boolean bFailedToSome = false; SendFailedException sendex = new SendFailedException("Unable to send message to some recipients"); // Try to send while there remain some potentially good addresses do { // Avoid a loop if we are stuck nAddresses = remainingAddresses.length; try { // Send to the list of remaining addresses, ignoring the addresses attached to the message Transport.send(message, remainingAddresses); } catch (SendFailedException ex) { bFailedToSome = true; sendex.setNextException(ex); // Extract the remaining potentially good addresses remainingAddresses = ex.getValidUnsentAddresses(); } } while (remainingAddresses != null && remainingAddresses.length > 0 && remainingAddresses.length != nAddresses); if (bFailedToSome) { throw sendex; } }
From source file:jp.mamesoft.mailsocketchat.Mail.java
public static void Send(String to, int mode) { //mode 0 = ?, 1 = ?, 2 = ?, 3 = ??, 4 = , 5 = System.out.println("???"); String from = Mailsocketchat.mail_user; String host = "smtp.gmail.com"; String port = "465"; String text = ""; String subject = ""; if (mode == 0) { text = logprint(text);//from ww w. j av a2s. com subject = " - MailSocketChat"; if (Mailsocketchat.newver) { text = text + "\n\n??????????\n"; } } if (mode == 1) { if (Mailsocketchat.subjectname) { subject = Mailsocketchat.logs.get(0).get("name"); } else { subject = "?? - MailSocketChat"; } text = logprint(text); } if (mode == 8) { text = logprint(text); subject = "?? - MailSocketChat"; } if (mode == 2) { if (!Mailsocketchat.push) { subject = "????? - MailSocketChat"; text = "???????????????????\n\n??????\n"; text = logprint(text); } else { subject = "??? - MailSocketChat"; text = "?????????????????\n(???????????)\n\n"; } if (Mailsocketchat.newver) { text = text + "\n\n??????????\n"; } } if (mode == 3) { if (!Mailsocketchat.push && !Mailsocketchat.repeat) { subject = "???? - MailSocketChat"; text = "????\n\n??????\n"; text = logprint(text); } else { subject = "?????? - MailSocketChat"; text = "?????????????????\n\n"; if (Mailsocketchat.repeat) { text = text + "??????\n"; text = logprint(text); } } if (Mailsocketchat.newver) { text = text + "\n\n??????????\n"; } } if (mode == 7) { if (!Mailsocketchat.repeat) { subject = "????? - MailSocketChat"; text = "?????30????????????\n\n"; if (!Mailsocketchat.push) { text = text + "??????\n"; text = logprint(text); } } else { subject = "??? - MailSocketChat"; text = "???\n\n"; } if (Mailsocketchat.newver) { text = text + "\n\n??????????\n"; } } if (mode == 4) { subject = " - MailSocketChat"; int userint = Mailsocketchat.users.size(); int romint = Mailsocketchat.roms.size(); text = ": " + userint + " ROM: " + romint + "\n\n\n"; for (Integer id : Mailsocketchat.users.keySet()) { HashMap<String, String> data = Mailsocketchat.users.get(id); text = text + data.get("name") + "\n"; text = text + " (" + data.get("ip") + ")\n"; } text = text + "\n\nROM\n"; for (Integer id : Mailsocketchat.roms.keySet()) { HashMap<String, String> data = Mailsocketchat.roms.get(id); text = text + data.get("ip") + "\n"; } if (Mailsocketchat.newver) { text = text + "\n\n??????????\n"; } } if (mode == 5) { subject = " - MailSocketChat"; if (Mailsocketchat.push) { text = "??: \n\n"; } else if (Mailsocketchat.repeat) { text = "??: \n\n"; } else { text = "??: ?\n\n"; } text = text + "?\n"; text = text + "?(fetch): ?????\n"; text = text + "(push): ????\n"; text = text + "(repeat): ????\n"; text = text + "(list): ???\n"; text = text + "#: ?????\n"; text = text + "#hoge: ??hoge????\n"; text = text + "(help): ?????\n\n"; text = text + "\nMailSocketChat Ver." + Mailsocketchat.version + "\n"; if (Mailsocketchat.newver) { text = text + "??????????\n"; } } if (mode == 6) { subject = "????????? - MailSocketChat"; text = text + "MailSocketChat??????????????????\n"; } // create some properties and get the default Session Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.transport.protocol", "smtps"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); Session sendsession = Session.getInstance(props, new PlainAuthenticator(Mailsocketchat.mail_user, Mailsocketchat.mail_pass)); try { // create a message MimeMessage msg = new MimeMessage(sendsession); msg.setFrom(new InternetAddress(from)); InternetAddress[] sendaddress = { new InternetAddress(to) }; msg.setRecipients(Message.RecipientType.TO, sendaddress); msg.setSubject(subject); msg.setSentDate(new Date()); // If the desired charset is known, you can use // setText(text, charset) msg.setText(text); Transport.send(msg); System.out.println("?????"); } catch (MessagingException mex) { System.out.println("??????"); } }
From source file:mitm.common.tools.SendMail.java
private static void prepareMessage(MimeMessage message, String from, String subject) throws MessagingException { message.setSentDate(new Date()); if (from != null) { message.setFrom(new InternetAddress(from)); }/* ww w. j a v a2 s. c om*/ if (subject != null) { message.setSubject(subject); } }
From source file:org.apache.usergrid.apm.service.util.Mailer.java
public static void send(String recipeintEmail, String subject, String messageText) { /*/*from w ww .ja v a2s . c om*/ * It is a good practice to put this in a java.util.Properties file and * encrypt password. Scroll down to comments below to see how to use * java.util.Properties in JSF context. */ Properties props = new Properties(); try { props.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("conf/email.properties")); } catch (IOException e) { e.printStackTrace(); } final String senderEmail = props.getProperty("mail.smtp.sender.email"); final String smtpUser = props.getProperty("mail.smtp.user"); final String senderName = props.getProperty("mail.smtp.sender.name"); final String senderPassword = props.getProperty("senderPassword"); final String emailtoCC = props.getProperty("instaopsOpsEmailtoCC"); Session session = Session.getDefaultInstance(props, new Authenticator() { @Override public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(smtpUser, senderPassword); } }); session.setDebug(false); try { MimeMessage message = new MimeMessage(session); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(messageText, "text/html"); // Add message text Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); message.setContent(multipart); message.setSubject(subject); InternetAddress senderAddress = new InternetAddress(senderEmail, senderName); message.setFrom(senderAddress); message.addRecipient(Message.RecipientType.CC, new InternetAddress(emailtoCC)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipeintEmail)); Transport.send(message); log.info("email sent"); } catch (MessagingException m) { log.error(m.toString()); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:javamailclient.GmailAPI.java
/** * Create a MimeMessage using the parameters provided. * * @param to Email address of the receiver. * @param from Email address of the sender, the mailbox account. * @param subject Subject of the email.//w ww .j ava 2 s. c om * @param bodyText Body text of the email. * @return MimeMessage to be used to send email. * @throws MessagingException */ public static MimeMessage createEmail(String to, String from, String subject, String bodyText) throws MessagingException { Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); MimeMessage email = new MimeMessage(session); InternetAddress tAddress = new InternetAddress(to); InternetAddress fAddress = new InternetAddress(from); email.setFrom(new InternetAddress(from)); email.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to)); email.setSubject(subject); email.setText(bodyText); return email; }
From source file:no.kantega.publishing.modules.mailsender.MailSender.java
/** * Sends a mail message. The content must be provided as MimeBodyPart objects. * * @param from Sender's email address. * @param to Recipient's email address. * @param cc Email address for CC. * @param bcc Email address for BCC. * @param subject Subject text for the email. * @param bodyParts The body parts to insert into the message. * @throws SystemException if an unexpected error occurs. * @throws ConfigurationException if a configuration error occurs. *///w w w . j av a 2 s. c o m public static void send(String from, String to, String cc, String bcc, String subject, MimeBodyPart[] bodyParts) throws ConfigurationException, SystemException { initEventLog(); try { Properties props = new Properties(); Configuration config = Aksess.getConfiguration(); String host = config.getString("mail.host"); if (host == null) { throw new ConfigurationException("mail.host"); } // I noen tilfeller nsker vi at all epost skal g til en testadresse String catchAllTo = config.getString("mail.catchall.to"); boolean catchallExists = catchAllTo != null && catchAllTo.contains("@"); if (catchallExists) { StringBuilder prefix = new StringBuilder(" (original recipient: " + to); if (cc != null) { prefix.append(", cc: ").append(cc); } if (bcc != null) { prefix.append(", bcc: ").append(bcc); } prefix.append(") "); subject = prefix + subject; to = catchAllTo; cc = null; bcc = null; } props.setProperty("mail.smtp.host", host); Session session = Session.getDefaultInstance(props); boolean debug = config.getBoolean("mail.debug", false); if (debug) { session.setDebug(true); } // Opprett message, sett attributter MimeMessage message = new MimeMessage(session); InternetAddress fromAddress = new InternetAddress(from); InternetAddress toAddress[] = InternetAddress.parse(to); message.setFrom(fromAddress); if (toAddress.length > 1) { message.setRecipients(Message.RecipientType.BCC, toAddress); } else { message.setRecipients(Message.RecipientType.TO, toAddress); } if (cc != null) { message.addRecipients(Message.RecipientType.CC, cc); } if (bcc != null) { message.addRecipients(Message.RecipientType.BCC, bcc); } message.setSubject(subject, "ISO-8859-1"); message.setSentDate(new Date()); Multipart mp = new MimeMultipart(); for (MimeBodyPart bodyPart : bodyParts) { mp.addBodyPart(bodyPart); } message.setContent(mp); // Send meldingen Transport.send(message); eventLog.log("System", null, Event.EMAIL_SENT, to + ":" + subject, null); // Logg sending log.info("Sending email to " + to + " with subject " + subject); } catch (MessagingException e) { String errormessage = "Subject: " + subject + " | Error: " + e.getMessage(); eventLog.log("System", null, Event.FAILED_EMAIL_SUBMISSION, errormessage + " | to: " + to, null); log.error("Error sending mail", e); throw new SystemException("Error sending email to : " + to + " with subject " + subject, e); } }
From source file:javamailclient.GmailAPI.java
/** * Create a MimeMessage using the parameters provided. * * @param to Email address of the receiver. * @param from Email address of the sender, the mailbox account. * @param subject Subject of the email.//from w w w . j av a 2 s . co m * @param bodyText Body text of the email. * @param fileDir Path to the directory containing attachment. * @param filename Name of file to be attached. * @return MimeMessage to be used to send email. * @throws MessagingException */ public static MimeMessage createEmailWithAttachment(String to, String from, String subject, String bodyText, String fileDir, String filename) throws MessagingException, IOException { Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); MimeMessage email = new MimeMessage(session); InternetAddress tAddress = new InternetAddress(to); InternetAddress fAddress = new InternetAddress(from); email.setFrom(fAddress); email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress); email.setSubject(subject); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(bodyText, "text/plain"); mimeBodyPart.setHeader("Content-Type", "text/plain; charset=\"UTF-8\""); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(mimeBodyPart); mimeBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(fileDir + filename); mimeBodyPart.setDataHandler(new DataHandler(source)); mimeBodyPart.setFileName(filename); String contentType = Files.probeContentType(FileSystems.getDefault().getPath(fileDir, filename)); mimeBodyPart.setHeader("Content-Type", contentType + "; name=\"" + filename + "\""); mimeBodyPart.setHeader("Content-Transfer-Encoding", "base64"); multipart.addBodyPart(mimeBodyPart); email.setContent(multipart); return email; }
From source file:gmailclientfx.core.GmailClient.java
public static void sendMessage(String to, String subject, String body, List<String> attachments) throws Exception { // authenticate with gmail smtp server SMTPTransport smtpTransport = connectToSmtp("smtp.gmail.com", 587, EMAIL, ACCESS_TOKEN, true); // kreiraj MimeMessage objekt MimeMessage msg = new MimeMessage(OAuth2Authenticator.getSession()); // dodaj headere msg.addHeader("Content-type", "text/HTML; charset=UTF-8"); msg.addHeader("format", "flowed"); msg.addHeader("Content-Transfer-Encoding", "8bit"); msg.setFrom(new InternetAddress(EMAIL)); msg.setRecipients(javax.mail.Message.RecipientType.CC, InternetAddress.parse(to)); msg.setSubject(subject, "UTF-8"); msg.setReplyTo(InternetAddress.parse(EMAIL, false)); // tijelo poruke BodyPart msgBodyPart = new MimeBodyPart(); msgBodyPart.setText(body);// w w w . j a va 2s . c om Multipart multipart = new MimeMultipart(); multipart.addBodyPart(msgBodyPart); msg.setContent(multipart); // dodaj privitke if (attachments.size() > 0) { for (String attachment : attachments) { msgBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(attachment); msgBodyPart.setDataHandler(new DataHandler(source)); msgBodyPart.setFileName(source.getName()); multipart.addBodyPart(msgBodyPart); } msg.setContent(multipart); } smtpTransport.sendMessage(msg, InternetAddress.parse(to)); Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle("Poruka poslana!"); alert.setHeaderText(null); alert.setContentText("Email uspjeno poslan!"); alert.showAndWait(); }
From source file:org.apache.juddi.subscription.notify.USERFRIENDLYSMTPNotifier.java
public static void notifyAccountDeleted(TemporaryMailContainer container) { try {//from w w w. ja v a 2 s. co m Publisher publisher = container.getPublisher(); Publisher deletedBy = container.getDeletedBy(); 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 Multipart mp = new MimeMultipart(); MimeBodyPart content = new MimeBodyPart(); String msg_content = ResourceConfig.getGlobalMessage("notifications.smtp.accountDeleted"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd kk:mm:ssZ"); //Hello %s, %s,<br><br>Your account has been 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); message.setContent(mp); message.setSubject(ResourceConfig.getGlobalMessage("notifications.smtp.accountDeleted.subject")); Transport.send(message); } catch (Throwable t) { log.warn("Error sending email!" + t.getMessage()); log.debug("Error sending email!" + t.getMessage(), t); } }