List of usage examples for javax.mail Message setContent
public void setContent(Object obj, String type) throws MessagingException;
From source file:smilehouse.opensyncro.pipes.Pipe.java
private void addLogEntry(LogEntry logEntry, int statusCode) { if (this.log == null) this.log = new HashSet(); logEntry.setStatusCode(statusCode);/*from w w w . j a v a 2 s . c o m*/ logEntry.setTime(new Date()); // The LogEntry is not explicitly added to the Pipe's log Set, since it causes // Hibernate to query all LogEntries from the database and thus consume // ever-increasing amount of server resources. //this.log.add(logEntry); String status = getStatusString(statusCode); Persister persister = new Persister(database); try { persister.update(logEntry); List messages; boolean mailAddressNotSet = ((getMailHost() == null || getRecipientAddress() == null) || (getMailHost().length() == 0 || getRecipientAddress().length() == 0)); // Notification via email only if host and email address are present if (!mailAddressNotSet && !(getTransferLogNotificationLevel() == MessageLogger.MAIL_NONE)) { String date = dateFormat.format(new Date()); String subject = this.getName() + " " + status + " " + date + " (" + database + ")"; String message = ""; // Get number of log messages at or below transferLogNotificationLevel. int entries = persister.getLogMessageEntries(logEntry.getId(), getTransferLogNotificationLevel()) .size(); //Generate mail message if (entries > 0) { messages = persister.getLogMessageEntries(logEntry.getId(), getLoggingVerbosityLevel()); for (Iterator m = messages.iterator(); m.hasNext();) { LogMessageEntry messageEntry = (LogMessageEntry) m.next(); message += (messageEntry.getMessage()) + "\n"; } } else { message += MAIL_MESSAGE_NO_ENTRIES; } // Send notification email except when the message is // MAIL_MESSAGE_NO_ENTRIES or the pipe has aborted and // isAbortMailEnabled()==true if (!message.equals(MAIL_MESSAGE_NO_ENTRIES) || (statusCode == LogEntry.STATUS_ABORTED && isAbortMailEnabled())) { try { Properties props = new Properties(); props.put("mail.host", getMailHost()); Session mailConnection = Session.getInstance(props, null); Message msg = new MimeMessage(mailConnection); Address sender = new InternetAddress(MAIL_SENDER + "@" + getMailHost(), MAIL_SENDER); Address[] receivers = receiverAddresses(getRecipientAddress()); // Set mail content and subject msg.setContent(message, "text/plain"); msg.setFrom(sender); msg.setRecipients(Message.RecipientType.TO, receivers); msg.setSubject(subject); // Send the mail Transport.send(msg); } catch (MessagingException e) { String error = "An error occurred when sending mail report from " + MAIL_SENDER + "@" + getMailHost() + " to " + getRecipientAddress() + ":\n" + e.getMessage(); Environment.getInstance().log(error); logEntry.logMessage(error, this, MessageLogger.ERROR); persister.update(logEntry); } catch (RuntimeException ex) { Environment.getInstance().log("A RuntimeException has occurred: " + ex.getMessage() + ex.getStackTrace().toString()); } } } // Remove unnecessary (debug level) messages from the LogEntry if Transfer log // verbosity level is set to DYNAMIC and the current LogEntry's status is either // OK or ABORTED if (getLoggingVerbosityLevel() == MessageLogger.LOG_DYNAMIC && (statusCode == LogEntry.STATUS_OK || statusCode == LogEntry.STATUS_ABORTED)) { messages = persister.getLogMessageEntries(logEntry.getId(), MessageLogger.DEBUG); if (messages.size() > 0) { for (Iterator m = messages.iterator(); m.hasNext();) { LogMessageEntry messageEntry = (LogMessageEntry) m.next(); if (messageEntry.getMessageType() == MessageLogger.DEBUG) { persister.delete(messageEntry); } } } } } catch (Exception e) { Environment.getInstance().log(e.getMessage()); } finally { persister.close(); } }
From source file:com.tremolosecurity.provisioning.core.ProvisioningEngineImpl.java
private void sendEmail(SmtpMessage msg) throws MessagingException { Properties props = new Properties(); boolean doAuth = false; props.setProperty("mail.smtp.host", prov.getSmtpHost()); props.setProperty("mail.smtp.port", Integer.toString(prov.getSmtpPort())); if (prov.getSmtpUser() != null && !prov.getSmtpUser().isEmpty()) { logger.debug("SMTP user found '" + prov.getSmtpUser() + "', enabling authentication"); props.setProperty("mail.smtp.user", prov.getSmtpUser()); props.setProperty("mail.smtp.auth", "true"); doAuth = true;//from w w w . ja va 2 s . c o m } else { logger.debug("No SMTP user, disabling authentication"); doAuth = false; props.setProperty("mail.smtp.auth", "false"); } props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.smtp.starttls.enable", Boolean.toString(prov.isSmtpTLS())); if (logger.isDebugEnabled()) { props.setProperty("mail.debug", "true"); props.setProperty("mail.socket.debug", "true"); } if (prov.getLocalhost() != null && !prov.getLocalhost().isEmpty()) { props.setProperty("mail.smtp.localhost", prov.getLocalhost()); } if (prov.isUseSOCKSProxy()) { props.setProperty("mail.smtp.socks.host", prov.getSocksProxyHost()); props.setProperty("mail.smtp.socks.port", Integer.toString(prov.getSocksProxyPort())); props.setProperty("mail.smtps.socks.host", prov.getSocksProxyHost()); props.setProperty("mail.smtps.socks.port", Integer.toString(prov.getSocksProxyPort())); } //Session session = Session.getInstance(props, new SmtpAuthenticator(this.smtpUser,this.smtpPassword)); Session session = null; if (doAuth) { logger.debug("Creating authenticated session"); session = Session.getInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(prov.getSmtpUser(), prov.getSmtpPassword()); } }); } else { logger.debug("Creating unauthenticated session"); session = Session.getInstance(props); } if (logger.isDebugEnabled()) { session.setDebugOut(System.out); session.setDebug(true); } //Transport tr = session.getTransport("smtp"); //tr.connect(); //tr.connect(this.smtpHost,this.smtpPort, this.smtpUser, this.smtpPassword); Message msgToSend = new MimeMessage(session); msgToSend.setFrom(new InternetAddress(msg.from)); msgToSend.addRecipient(Message.RecipientType.TO, new InternetAddress(msg.to)); msgToSend.setSubject(msg.subject); if (msg.contentType != null) { msgToSend.setContent(msg.msg, msg.contentType); } else { msgToSend.setText(msg.msg); } msgToSend.saveChanges(); Transport.send(msgToSend); //tr.sendMessage(msg, msg.getAllRecipients()); //tr.close(); }
From source file:org.sofun.platform.notification.NotificationServiceImpl.java
@Override public void sendEmail(Member member, Map<String, String> params) throws CoreException { final String emailsStr = params.get("emails"); String[] emails = null;//from w ww . jav a2s . co m if (emailsStr != null) { emails = params.get("emails").split(","); } String format = params.get("format"); if (format == null) { format = "text/html"; } Message message = new MimeMessage(mailer); final String encodingOptions = format + "; charset=UTF-8"; try { message.setHeader("Content-Type", encodingOptions); String from = params.get("from"); if (from == null || from.equals("")) { message.setFrom(new InternetAddress(CoreConstants.SOFUN_MAIL_FROM)); } else { message.setFrom(new InternetAddress(from)); } InternetAddress to[] = null; if (emails == null) { to = new InternetAddress[1]; to[0] = new InternetAddress(member.getEmail()); } else { to = new InternetAddress[emails.length]; for (int i = 0; i < emails.length; i++) { to[i] = new InternetAddress(emails[i]); } } message.setRecipients(Message.RecipientType.TO, to); message.setSubject(params.get("subject")); String body = params.get("body"); if (body != null) { body = body.replaceAll("(\\r|\\n)", "<p/>"); } VelocityEngine ve = null; try { ve = getVelocityEngine(); } catch (Exception e) { throw new CoreException(e.getMessage()); } Template t = ve.getTemplate(params.get("templateId")); StringWriter writer = new StringWriter(); VelocityContext context = new VelocityContext(); // Add Member in velocity context. context.put("member", member); context.put("body", body); // Add all incoming params in velocity context. for (Map.Entry<String, String> entry : params.entrySet()) { context.put(entry.getKey(), entry.getValue()); } t.merge(context, writer); message.setContent(writer.toString(), encodingOptions); Transport.send(message); String logEmails; if (emails != null) { logEmails = emailsStr; } else { logEmails = member.getEmail(); } log.info("Sending an email to=" + logEmails); } catch (MessagingException e) { log.error("Failed to send an email. See error below."); throw new CoreException(e.getMessage()); } }
From source file:com.akretion.kettle.steps.terminatooor.ScriptValuesAddedFunctions.java
public static void sendMail(ScriptEngine actualContext, Bindings actualObject, Object[] ArgList, Object FunctionContext) { boolean debug = false; // Arguments: // String smtp, String from, String recipients[ ], String subject, String message if (ArgList.length == 5) { try {//from ww w. jav a 2 s . co m //Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", ArgList[0]); // create some properties and get the default Session Session session = Session.getDefaultInstance(props, null); session.setDebug(debug); // create a message Message msg = new MimeMessage(session); // set the from and to address InternetAddress addressFrom = new InternetAddress((String) ArgList[1]); msg.setFrom(addressFrom); // Get Recipients String strArrRecipients[] = ((String) ArgList[2]).split(","); InternetAddress[] addressTo = new InternetAddress[strArrRecipients.length]; for (int i = 0; i < strArrRecipients.length; i++) { addressTo[i] = new InternetAddress(strArrRecipients[i]); } msg.setRecipients(Message.RecipientType.TO, addressTo); // Optional : You can also set your custom headers in the Email if you Want msg.addHeader("MyHeaderName", "myHeaderValue"); // Setting the Subject and Content Type msg.setSubject((String) ArgList[3]); msg.setContent((String) ArgList[4], "text/plain"); Transport.send(msg); } catch (Exception e) { throw new RuntimeException("sendMail: " + e.toString()); } } else { throw new RuntimeException("The function call sendMail requires 5 arguments."); } }
From source file:com.panet.imeta.trans.steps.scriptvalues_mod.ScriptValuesAddedFunctions.java
public static void sendMail(Context actualContext, Scriptable actualObject, Object[] ArgList, Function FunctionContext) { boolean debug = false; // Arguments: // String smtp, String from, String recipients[ ], String subject, String message if (ArgList.length == 5) { try {//from w w w . ja v a2 s .co m //Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", ArgList[0]); // create some properties and get the default Session Session session = Session.getDefaultInstance(props, null); session.setDebug(debug); // create a message Message msg = new MimeMessage(session); // set the from and to address InternetAddress addressFrom = new InternetAddress((String) ArgList[1]); msg.setFrom(addressFrom); // Get Recipients String strArrRecipients[] = ((String) ArgList[2]).split(","); InternetAddress[] addressTo = new InternetAddress[strArrRecipients.length]; for (int i = 0; i < strArrRecipients.length; i++) { addressTo[i] = new InternetAddress(strArrRecipients[i]); } msg.setRecipients(Message.RecipientType.TO, addressTo); // Optional : You can also set your custom headers in the Email if you Want msg.addHeader("MyHeaderName", "myHeaderValue"); // Setting the Subject and Content Type msg.setSubject((String) ArgList[3]); msg.setContent((String) ArgList[4], "text/plain"); Transport.send(msg); } catch (Exception e) { throw Context.reportRuntimeError("sendMail: " + e.toString()); } } else { throw Context.reportRuntimeError("The function call sendMail requires 5 arguments."); } }
From source file:org.pentaho.di.trans.steps.script.ScriptAddedFunctions.java
public static void sendMail(ScriptEngine actualContext, Bindings actualObject, Object[] ArgList, Object FunctionContext) { boolean debug = false; // Arguments: // String smtp, String from, String recipients[ ], String subject, String message if (ArgList.length == 5) { try {//from ww w . ja v a 2 s. c om // Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", ArgList[0]); // create some properties and get the default Session Session session = Session.getDefaultInstance(props, null); session.setDebug(debug); // create a message Message msg = new MimeMessage(session); // set the from and to address InternetAddress addressFrom = new InternetAddress((String) ArgList[1]); msg.setFrom(addressFrom); // Get Recipients String[] strArrRecipients = ((String) ArgList[2]).split(","); InternetAddress[] addressTo = new InternetAddress[strArrRecipients.length]; for (int i = 0; i < strArrRecipients.length; i++) { addressTo[i] = new InternetAddress(strArrRecipients[i]); } msg.setRecipients(Message.RecipientType.TO, addressTo); // Optional : You can also set your custom headers in the Email if you Want msg.addHeader("MyHeaderName", "myHeaderValue"); // Setting the Subject and Content Type msg.setSubject((String) ArgList[3]); msg.setContent(ArgList[4], "text/plain"); Transport.send(msg); } catch (Exception e) { throw new RuntimeException("sendMail: " + e.toString()); } } else { throw new RuntimeException("The function call sendMail requires 5 arguments."); } }
From source file:com.nridge.core.app.mail.MailManager.java
/** * If the property "delivery_enabled" is <i>true</i>, then this * method will deliver the subject and message via an email * transport (e.g. SMTP)./*from w ww .j a va 2s . c o m*/ * * @param aSubject Message subject. * @param aMessage Message content. * * @throws IOException I/O related error condition. * @throws NSException Missing configuration properties. * @throws MessagingException Message subsystem error condition. */ public void sendMessage(String aSubject, String aMessage) throws IOException, NSException, MessagingException { InternetAddress internetAddressFrom, internetAddressTo; Logger appLogger = mAppMgr.getLogger(this, "sendMessage"); appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER); if (isCfgStringTrue("delivery_enabled")) { if ((StringUtils.isNotEmpty(aSubject)) && (StringUtils.isNotEmpty(aMessage))) { initialize(); String propertyName = "address_to"; Message mimeMessage = new MimeMessage(mMailSession); if (mAppMgr.isPropertyMultiValue(getCfgString(propertyName))) { String[] addressToArray = mAppMgr.getStringArray(getCfgString(propertyName)); for (String mailAddressTo : addressToArray) { internetAddressTo = new InternetAddress(mailAddressTo); mimeMessage.addRecipient(MimeMessage.RecipientType.TO, internetAddressTo); } } else { String mailAddressTo = getCfgString(propertyName); if (StringUtils.isEmpty(mailAddressTo)) { String msgStr = String.format("Mail Manager property '%s' is undefined.", mCfgPropertyPrefix + "." + propertyName); appLogger.error(msgStr); throw new NSException(msgStr); } internetAddressTo = new InternetAddress(mailAddressTo); mimeMessage.addRecipient(MimeMessage.RecipientType.TO, internetAddressTo); } propertyName = "address_from"; String mailAddressFrom = getCfgString(propertyName); if (StringUtils.isEmpty(mailAddressFrom)) { String msgStr = String.format("Mail Manager property '%s' is undefined.", mCfgPropertyPrefix + "." + propertyName); appLogger.error(msgStr); throw new NSException(msgStr); } internetAddressFrom = new InternetAddress(mailAddressFrom); mimeMessage.addFrom(new InternetAddress[] { internetAddressFrom }); mimeMessage.setSubject(aSubject); mimeMessage.setContent(aMessage, "text/plain"); appLogger.debug(String.format("Mail Message (%s): %s", aSubject, aMessage)); Transport.send(mimeMessage); } else throw new NSException("Subject and message are required parameters."); } else appLogger.warn("Email delivery is not enabled - no message will be sent."); appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART); }
From source file:org.pentaho.di.trans.steps.scriptvalues_mod.ScriptValuesAddedFunctions.java
public static void sendMail(Context actualContext, Scriptable actualObject, Object[] ArgList, Function FunctionContext) { boolean debug = false; // Arguments: // String smtp, String from, String recipients[ ], String subject, String message if (ArgList.length == 5) { try {//from ww w .ja v a 2 s . c o m // Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", ArgList[0]); // create some properties and get the default Session Session session = Session.getDefaultInstance(props, null); session.setDebug(debug); // create a message Message msg = new MimeMessage(session); // set the from and to address InternetAddress addressFrom = new InternetAddress((String) ArgList[1]); msg.setFrom(addressFrom); // Get Recipients String[] strArrRecipients = ((String) ArgList[2]).split(","); InternetAddress[] addressTo = new InternetAddress[strArrRecipients.length]; for (int i = 0; i < strArrRecipients.length; i++) { addressTo[i] = new InternetAddress(strArrRecipients[i]); } msg.setRecipients(Message.RecipientType.TO, addressTo); // Optional : You can also set your custom headers in the Email if you Want msg.addHeader("MyHeaderName", "myHeaderValue"); // Setting the Subject and Content Type msg.setSubject((String) ArgList[3]); msg.setContent(ArgList[4], "text/plain"); Transport.send(msg); } catch (Exception e) { throw Context.reportRuntimeError("sendMail: " + e.toString()); } } else { throw Context.reportRuntimeError("The function call sendMail requires 5 arguments."); } }
From source file:com.clustercontrol.jobmanagement.util.SendApprovalMail.java
/** * ????//from w w w .j a v a 2s . c o m * @param toAddressStr * ?To * @param ccAddressStr * ?Cc * @param subject * ?? * @param content * * @throws MessagingException * @throws UnsupportedEncodingException */ public void sendMail(String[] toAddressStr, String[] ccAddressStr, String subject, String content) throws MessagingException, UnsupportedEncodingException { if (toAddressStr == null || toAddressStr.length <= 0) { // ?? return; } /* * https://javamail.java.net/nonav/docs/api/com/sun/mail/smtp/package-summary.html */ Properties _properties = new Properties(); _properties.setProperty("mail.debug", Boolean.toString(HinemosPropertyUtil.getHinemosPropertyBool("mail.debug", false))); _properties.setProperty("mail.store.protocol", HinemosPropertyUtil.getHinemosPropertyStr("mail.store.protocol", "pop3")); String protocol = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.protocol", "smtp"); _properties.setProperty("mail.transport.protocol", protocol); _properties.put("mail.smtp.socketFactory", javax.net.SocketFactory.getDefault()); _properties.put("mail.smtp.ssl.socketFactory", javax.net.ssl.SSLSocketFactory.getDefault()); setProperties(_properties, "mail." + protocol + ".user", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".host", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".port", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".connectiontimeout", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".timeout", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".writetimeout", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".from", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".localhost", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".localaddress", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".localport", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".ehlo", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.mechanisms", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".auth.login.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.plain.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.digest-md5.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.ntlm.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.ntlm.domain", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".auth.ntlm.flags", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".submitter", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".dsn.notify", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".dsn.ret", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".allow8bitmime", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".sendpartial", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".sasl.enable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".sasl.mechanisms", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".sasl.authorizationid", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".sasl.realm", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".sasl.usecanonicalhostname", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".quitwait", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".reportsuccess", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".socketFactory.class", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".socketFactory.fallback", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".socketFactory.port", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".starttls.enable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".starttls.required", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".socks.host", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".socks.port", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".mailextension", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".userset", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".noop.strict", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail.smtp.ssl.enable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail.smtp.ssl.checkserveridentity", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail.smtp.ssl.trust", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail.smtp.ssl.socketFactory.class", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail.smtp.ssl.socketFactory.port", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail.smtp.ssl.protocols", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail.smtp.ssl.ciphersuites", HinemosPropertyTypeConstant.TYPE_STRING); /** * ?DB?? */ String _loginUser = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.user", "nobody"); String _loginPassword = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.password", "password"); String _fromAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.from.address", "admin@hinemos.com"); String _fromPersonalName = HinemosPropertyUtil.getHinemosPropertyStr("mail.from.personal.name", "Hinemos Admin"); _fromPersonalName = convertNativeToAscii(_fromPersonalName); String _replyToAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.reply.to.address", "admin@hinemos.com"); String _replyToPersonalName = HinemosPropertyUtil.getHinemosPropertyStr("mail.reply.personal.name", "Hinemos Admin"); _replyToPersonalName = convertNativeToAscii(_replyToPersonalName); String _errorsToAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.errors.to.address", "admin@hinemos.com"); int _transportTries = HinemosPropertyUtil.getHinemosPropertyNum("mail.transport.tries", Long.valueOf(1)) .intValue(); int _transportTriesInterval = HinemosPropertyUtil .getHinemosPropertyNum("mail.transport.tries.interval", Long.valueOf(10000)).intValue(); String _charsetAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.address", _charsetAddressDefault); String _charsetSubject = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.subject", _charsetSubjectDefault); String _charsetContent = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.content", _charsetContentDefault); m_log.debug("initialized mail sender : from_address = " + _fromAddress + ", From = " + _fromPersonalName + " <" + _replyToAddress + ">" + ", Reply-To = " + _replyToPersonalName + " <" + _replyToAddress + ">" + ", Errors-To = " + _errorsToAddress + ", tries = " + _transportTries + ", tries-interval = " + _transportTriesInterval + ", Charset [address:subject:content] = [" + _charsetAddress + ":" + _charsetSubject + ":" + _charsetContent + "]"); // JavaMail Session Session session = Session.getInstance(_properties); Message mineMsg = new MimeMessage(session); // ????? if (_fromAddress != null && _fromPersonalName != null) { mineMsg.setFrom(new InternetAddress(_fromAddress, _fromPersonalName, _charsetAddress)); } else if (_fromAddress != null && _fromPersonalName == null) { mineMsg.setFrom(new InternetAddress(_fromAddress)); } // REPLY-TO if (_replyToAddress != null && _replyToPersonalName != null) { InternetAddress reply[] = { new InternetAddress(_replyToAddress, _replyToPersonalName, _charsetAddress) }; mineMsg.setReplyTo(reply); mineMsg.reply(true); } else if (_replyToAddress != null && _replyToPersonalName == null) { InternetAddress reply[] = { new InternetAddress(_replyToAddress) }; mineMsg.setReplyTo(reply); mineMsg.reply(true); } // ERRORS-TO if (_errorsToAddress != null) { mineMsg.setHeader("Errors-To", _errorsToAddress); } // ? // TO InternetAddress[] toAddress = this.getAddress(toAddressStr); if (toAddress != null && toAddress.length > 0) { mineMsg.setRecipients(javax.mail.Message.RecipientType.TO, toAddress); } else { return; // TO? } // CC if (ccAddressStr != null) { InternetAddress[] ccAddress = this.getAddress(ccAddressStr); if (ccAddress != null && ccAddress.length > 0) { mineMsg.setRecipients(javax.mail.Message.RecipientType.CC, ccAddress); } } String message = "TO=" + Arrays.asList(toAddressStr); if (ccAddressStr != null) { message += ", CC=" + Arrays.asList(ccAddressStr); } m_log.debug(message); // ??? mineMsg.setSubject(MimeUtility.encodeText(subject, _charsetSubject, "B")); // ? mineMsg.setContent(content, "text/plain; charset=" + _charsetContent); // ? mineMsg.setSentDate(HinemosTime.getDateInstance()); // ???true?????? for (int i = 0; i < _transportTries; i++) { Transport transport = null; try { // ? transport = session.getTransport(); boolean flag = HinemosPropertyUtil.getHinemosPropertyBool("mail." + protocol + ".auth", false); if (flag) { transport.connect(_loginUser, _loginPassword); } else { transport.connect(); } transport.sendMessage(mineMsg, mineMsg.getAllRecipients()); break; } catch (AuthenticationFailedException e) { throw e; } catch (SMTPAddressFailedException e) { throw e; } catch (MessagingException me) { //_transportTries?sleep??? if (i < (_transportTries - 1)) { m_log.info("sendMail() : retry sendmail. " + me.getMessage()); try { Thread.sleep(_transportTriesInterval); } catch (InterruptedException e) { } //_transportTries??INTERNAL????Exceptionthrow } else { throw me; } } finally { if (transport != null) { transport.close(); } } } }
From source file:com.clustercontrol.notify.util.SendMail.java
public void sendMail(String[] toAddressStr, String[] ccAddressStr, String[] bccAddressStr, String subject, String content) throws MessagingException, UnsupportedEncodingException { if (toAddressStr == null || toAddressStr.length <= 0) { // ??/*w ww . jav a 2 s. c om*/ return; } /* * https://javamail.java.net/nonav/docs/api/com/sun/mail/smtp/package-summary.html */ Properties _properties = new Properties(); _properties.setProperty("mail.debug", Boolean.toString(HinemosPropertyUtil.getHinemosPropertyBool("mail.debug", false))); _properties.setProperty("mail.store.protocol", HinemosPropertyUtil.getHinemosPropertyStr("mail.store.protocol", "pop3")); String protocol = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.protocol", "smtp"); _properties.setProperty("mail.transport.protocol", protocol); _properties.put("mail.smtp.socketFactory", javax.net.SocketFactory.getDefault()); _properties.put("mail.smtp.ssl.socketFactory", javax.net.ssl.SSLSocketFactory.getDefault()); setProperties(_properties, "mail." + protocol + ".user", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".host", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".port", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".connectiontimeout", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".timeout", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".writetimeout", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".from", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".localhost", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".localaddress", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".localport", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".ehlo", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.mechanisms", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".auth.login.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.plain.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.digest-md5.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.ntlm.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.ntlm.domain", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".auth.ntlm.flags", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".submitter", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".dsn.notify", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".dsn.ret", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".allow8bitmime", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".sendpartial", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".sasl.enable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".sasl.mechanisms", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".sasl.authorizationid", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".sasl.realm", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".sasl.usecanonicalhostname", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".quitwait", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".reportsuccess", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".socketFactory.class", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".socketFactory.fallback", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".socketFactory.port", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".starttls.enable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".starttls.required", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".socks.host", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".socks.port", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".mailextension", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".userset", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".noop.strict", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail.smtp.ssl.enable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail.smtp.ssl.checkserveridentity", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail.smtp.ssl.trust", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail.smtp.ssl.socketFactory.class", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail.smtp.ssl.socketFactory.port", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail.smtp.ssl.protocols", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail.smtp.ssl.ciphersuites", HinemosPropertyTypeConstant.TYPE_STRING); /** * ?DB?? */ String _loginUser = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.user", "nobody"); String _loginPassword = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.password", "password"); String _fromAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.from.address", "admin@hinemos.com"); String _fromPersonalName = HinemosPropertyUtil.getHinemosPropertyStr("mail.from.personal.name", "Hinemos Admin"); _fromPersonalName = convertNativeToAscii(_fromPersonalName); String _replyToAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.reply.to.address", "admin@hinemos.com"); String _replyToPersonalName = HinemosPropertyUtil.getHinemosPropertyStr("mail.reply.personal.name", "Hinemos Admin"); _replyToPersonalName = convertNativeToAscii(_replyToPersonalName); String _errorsToAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.errors.to.address", "admin@hinemos.com"); int _transportTries = HinemosPropertyUtil.getHinemosPropertyNum("mail.transport.tries", Long.valueOf(1)) .intValue(); int _transportTriesInterval = HinemosPropertyUtil .getHinemosPropertyNum("mail.transport.tries.interval", Long.valueOf(10000)).intValue(); String _charsetAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.address", _charsetAddressDefault); String _charsetSubject = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.subject", _charsetSubjectDefault); String _charsetContent = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.content", _charsetContentDefault); m_log.debug("initialized mail sender : from_address = " + _fromAddress + ", From = " + _fromPersonalName + " <" + _replyToAddress + ">" + ", Reply-To = " + _replyToPersonalName + " <" + _replyToAddress + ">" + ", Errors-To = " + _errorsToAddress + ", tries = " + _transportTries + ", tries-interval = " + _transportTriesInterval + ", Charset [address:subject:content] = [" + _charsetAddress + ":" + _charsetSubject + ":" + _charsetContent + "]"); // JavaMail Session Session session = Session.getInstance(_properties); Message mineMsg = new MimeMessage(session); // ????? if (_fromAddress != null && _fromPersonalName != null) { mineMsg.setFrom(new InternetAddress(_fromAddress, _fromPersonalName, _charsetAddress)); } else if (_fromAddress != null && _fromPersonalName == null) { mineMsg.setFrom(new InternetAddress(_fromAddress)); } // REPLY-TO if (_replyToAddress != null && _replyToPersonalName != null) { InternetAddress reply[] = { new InternetAddress(_replyToAddress, _replyToPersonalName, _charsetAddress) }; mineMsg.setReplyTo(reply); mineMsg.reply(true); } else if (_replyToAddress != null && _replyToPersonalName == null) { InternetAddress reply[] = { new InternetAddress(_replyToAddress) }; mineMsg.setReplyTo(reply); mineMsg.reply(true); } // ERRORS-TO if (_errorsToAddress != null) { mineMsg.setHeader("Errors-To", _errorsToAddress); } // ? // TO InternetAddress[] toAddress = this.getAddress(toAddressStr); if (toAddress != null && toAddress.length > 0) { mineMsg.setRecipients(javax.mail.Message.RecipientType.TO, toAddress); } else { return; // TO? } // CC if (ccAddressStr != null) { InternetAddress[] ccAddress = this.getAddress(ccAddressStr); if (ccAddress != null && ccAddress.length > 0) { mineMsg.setRecipients(javax.mail.Message.RecipientType.CC, ccAddress); } } // BCC if (bccAddressStr != null) { InternetAddress[] bccAddress = this.getAddress(bccAddressStr); if (bccAddress != null && bccAddress.length > 0) { mineMsg.setRecipients(javax.mail.Message.RecipientType.BCC, bccAddress); } } String message = "TO=" + Arrays.asList(toAddressStr); if (ccAddressStr != null) { message += ", CC=" + Arrays.asList(ccAddressStr); } if (bccAddressStr != null) { message += ", BCC=" + Arrays.asList(bccAddressStr); } m_log.debug(message); // ??? mineMsg.setSubject(MimeUtility.encodeText(subject, _charsetSubject, "B")); // ? mineMsg.setContent(content, "text/plain; charset=" + _charsetContent); // ? mineMsg.setSentDate(HinemosTime.getDateInstance()); // ???true?????? for (int i = 0; i < _transportTries; i++) { Transport transport = null; try { // ? transport = session.getTransport(); boolean flag = HinemosPropertyUtil.getHinemosPropertyBool("mail." + protocol + ".auth", false); if (flag) { transport.connect(_loginUser, _loginPassword); } else { transport.connect(); } transport.sendMessage(mineMsg, mineMsg.getAllRecipients()); break; } catch (AuthenticationFailedException e) { throw e; } catch (SMTPAddressFailedException e) { throw e; } catch (MessagingException me) { //_transportTries?sleep??? if (i < (_transportTries - 1)) { m_log.info("sendMail() : retry sendmail. " + me.getMessage()); try { Thread.sleep(_transportTriesInterval); } catch (InterruptedException e) { } //_transportTries??INTERNAL????Exceptionthrow } else { throw me; } } finally { if (transport != null) { transport.close(); } } } }