List of usage examples for javax.mail Transport sendMessage
public abstract void sendMessage(Message msg, Address[] addresses) throws MessagingException;
From source file:org.silverpeas.core.mail.engine.SmtpMailSender.java
/** * This method performs the treatment of the technical send: * <ul>/*from w w w. j a va2 s. c o m*/ * <li>connection to the SMTP server</li> * <li>sending</li> * <li>closing the connection</li> * </ul> * @param mail the original data from which the given {@link MimeMessage} has been initialized. * @param smtpConfiguration the SMTP configuration. * @param session the current mail session. * @param messageToSend the technical message to send. * @param batchedToAddresses the receivers of the message. * @throws MessagingException */ private void performSend(final MailToSend mail, final SmtpConfiguration smtpConfiguration, Session session, MimeMessage messageToSend, List<InternetAddress[]> batchedToAddresses) throws MessagingException { // Creating a Transport connection (TCP) final Transport transport; if (smtpConfiguration.isSecure()) { transport = session.getTransport(SmtpConfiguration.SECURE_TRANSPORT); } else { transport = session.getTransport(SmtpConfiguration.SIMPLE_TRANSPORT); } // Adding send reporting listener transport.addTransportListener(new SmtpMailSendReportListener(mail)); try { if (smtpConfiguration.isAuthenticate()) { transport.connect(smtpConfiguration.getServer(), smtpConfiguration.getPort(), smtpConfiguration.getUsername(), smtpConfiguration.getPassword()); } else { transport.connect(smtpConfiguration.getServer(), smtpConfiguration.getPort(), null, null); } for (InternetAddress[] toAddressBatch : batchedToAddresses) { messageToSend.setRecipients(mail.getTo().getRecipientType().getTechnicalType(), toAddressBatch); transport.sendMessage(messageToSend, toAddressBatch); } } finally { try { transport.close(); } catch (Exception e) { SilverTrace.error("mail", "SmtpMailSender.send()", "root.EX_IGNORED", "ClosingTransport", e); } } }
From source file:com.clustercontrol.jobmanagement.util.SendApprovalMail.java
/** * ????// www . j a v a2s. co 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) { // ??/*from w ww . ja v a2s .c o m*/ 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(); } } } }
From source file:com.autentia.tnt.mail.DefaultMailService.java
public void sendFiles(String to, String subject, String text, Collection<File> attachments) throws MessagingException { MimeMessage message = new MimeMessage(session); Transport t = session.getTransport("smtp"); message.setFrom(new InternetAddress(configurationUtil.getMailUsername())); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject);/* w w w . ja va2 s . c o m*/ message.setSentDate(new Date()); if (attachments == null || attachments.size() < 1) { message.setText(text); } else { // create the message part MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(text); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); for (File attachment : attachments) { messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(attachment); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(attachment.getName()); multipart.addBodyPart(messageBodyPart); } message.setContent(multipart); } t.connect(configurationUtil.getMailUsername(), configurationUtil.getMailPassword()); t.sendMessage(message, message.getAllRecipients()); t.close(); }
From source file:org.apache.jmeter.protocol.smtp.sampler.protocol.SendMailCommand.java
/** * Sends message to mailserver, waiting for delivery if using synchronous * mode.//from w w w.j ava 2 s . c o m * * @param message * Message previously prepared by prepareMessage() * @throws MessagingException * when problems sending the mail arise * @throws IOException * TODO can not see how * @throws InterruptedException * when interrupted while waiting for delivery in synchronous * modus */ public void execute(Message message) throws MessagingException, IOException, InterruptedException { Transport tr = null; try { tr = session.getTransport(getProtocol()); SynchronousTransportListener listener = null; if (synchronousMode) { listener = new SynchronousTransportListener(); tr.addTransportListener(listener); } if (useAuthentication) { tr.connect(smtpServer, username, password); } else { tr.connect(); } tr.sendMessage(message, message.getAllRecipients()); if (listener != null /*synchronousMode==true*/) { listener.attend(); // listener cannot be null here } } finally { if (tr != null) { try { tr.close(); } catch (Exception e) { // NOOP } } logger.debug("transport closed"); } logger.debug("message sent"); return; }
From source file:org.protocoderrunner.apprunner.api.PNetwork.java
@ProtocoderScript @APIMethod(description = "Send an E-mail. It requires passing a EmailConf object", example = "") @APIParam(params = { "url", "function(data)" }) public void sendEmail(String from, String to, String subject, String text, final EmailConf emailSettings) throws AddressException, MessagingException { if (emailSettings == null) { return;// ww w. jav a 2s. co m } // final String host = "smtp.gmail.com"; // final String address = "@gmail.com"; // final String pass = ""; Multipart multiPart; String finalString = ""; Properties props = System.getProperties(); props.put("mail.smtp.starttls.enable", emailSettings.ttl); props.put("mail.smtp.host", emailSettings.host); props.put("mail.smtp.user", emailSettings.user); props.put("mail.smtp.password", emailSettings.password); props.put("mail.smtp.port", emailSettings.port); props.put("mail.smtp.auth", emailSettings.auth); Log.i("Check", "done pops"); final Session session = Session.getDefaultInstance(props, null); DataHandler handler = new DataHandler(new ByteArrayDataSource(finalString.getBytes(), "text/plain")); final MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setDataHandler(handler); Log.i("Check", "done sessions"); multiPart = new MimeMultipart(); InternetAddress toAddress; toAddress = new InternetAddress(to); message.addRecipient(Message.RecipientType.TO, toAddress); Log.i("Check", "added recipient"); message.setSubject(subject); message.setContent(multiPart); message.setText(text); Thread t = new Thread(new Runnable() { @Override public void run() { try { MLog.i("check", "transport"); Transport transport = session.getTransport("smtp"); MLog.i("check", "connecting"); transport.connect(emailSettings.host, emailSettings.user, emailSettings.password); MLog.i("check", "wana send"); transport.sendMessage(message, message.getAllRecipients()); transport.close(); MLog.i("check", "sent"); } catch (AddressException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } } }); t.start(); }
From source file:egovframework.oe1.cms.cmm.notify.email.service.impl.EgovOe1SSLMailServiceImpl.java
protected void send(String subject, String content, String contentType) throws Exception { Properties props = new Properties(); props.put("mail.transport.protocol", "smtps"); props.put("mail.smtps.host", getHost()); props.put("mail.smtps.auth", "true"); Session mailSession = Session.getDefaultInstance(props); mailSession.setDebug(false);// www. ja v a 2 s .co m Transport transport = mailSession.getTransport(); MimeMessage message = new MimeMessage(mailSession); message.setFrom(new InternetAddress("www.egovframe.org", "webmaster", "euc-kr")); message.setSubject(subject); MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(content, "utf-8"); Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); List<String> fileNames = getAtchFileIds(); for (Iterator<String> it = fileNames.iterator(); it.hasNext();) { MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(it.next()); mbp2.setDataHandler(new DataHandler(fds)); mbp2.setFileName(MimeUtility.encodeText(fds.getName(), "euc-kr", "B")); // Q : ascii, B : mp.addBodyPart(mbp2); } // add the Multipart to the message message.setContent(mp); for (Iterator<String> it = getReceivers().iterator(); it.hasNext();) message.addRecipient(Message.RecipientType.TO, new InternetAddress(it.next())); transport.connect(getHost(), getPort(), getUsername(), getPassword()); transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO)); transport.close(); }
From source file:com.hs.mail.mailet.RemoteDelivery.java
/** * We arranged that the recipients are all going to the same mail server. We * will now rely on the DNS server to do DNS MX record lookup and try to * deliver to the multiple mail servers. If it fails, we should decide that * the failure is permanent or temporary. * /*from w ww. j a v a 2s.co m*/ * @param host * the same host of recipients * @param recipients * recipients who are all going to the same mail server * @param message * Mail object to be delivered * @param mimemsg * MIME message representation of the message * @return true if the delivery was successful or permanent failure so the * message should be deleted, otherwise false and the message will * be tried to send again later */ private boolean deliver(String host, Collection<Recipient> recipients, SmtpMessage message, MimeMessage mimemsg) { // Prepare javamail recipients InternetAddress[] addresses = new InternetAddress[recipients.size()]; Iterator<Recipient> it = recipients.iterator(); for (int i = 0; it.hasNext(); i++) { Recipient rcpt = it.next(); addresses[i] = rcpt.toInternetAddress(); } try { // Lookup the possible targets Iterator<HostAddress> targetServers = null; if (null == gateway) { targetServers = getSmtpHostAddresses(host); } else { targetServers = getGatewaySmtpHostAddresses(gateway); } if (!targetServers.hasNext()) { logger.info("No mail server found for: " + host); StringBuilder exceptionBuffer = new StringBuilder(128) .append("There are no DNS entries for the hostname ").append(host) .append(". I cannot determine where to send this message."); return failMessage(message, addresses, new MessagingException(exceptionBuffer.toString()), false); } Properties props = session.getProperties(); if (message.isNotificationMessage()) { props.put("mail.smtp.from", "<>"); } else { props.put("mail.smtp.from", message.getFrom().getMailbox()); } MessagingException lastError = null; StringBuilder logBuffer = null; HostAddress outgoingMailServer = null; while (targetServers.hasNext()) { try { outgoingMailServer = targetServers.next(); logBuffer = new StringBuilder(256).append("Attempting to deliver message to host ") .append(outgoingMailServer.getHostName()).append(" at ") .append(outgoingMailServer.getHost()).append(" for addresses ") .append(Arrays.asList(addresses)); logger.info(logBuffer.toString()); Transport transport = null; try { transport = session.getTransport(outgoingMailServer); try { if (authUser != null) { transport.connect(outgoingMailServer.getHostName(), authUser, authPass); } else { transport.connect(); } } catch (MessagingException e) { // Any error on connect should cause the mailet to // attempt to connect to the next SMTP server // associated with this MX record. logger.error(e.getMessage()); continue; } transport.sendMessage(mimemsg, addresses); } finally { if (transport != null) { try { transport.close(); } catch (MessagingException e) { } transport = null; } } logBuffer = new StringBuilder(256).append("Successfully sent message to host ") .append(outgoingMailServer.getHostName()).append(" at ") .append(outgoingMailServer.getHost()).append(" for addresses ") .append(Arrays.asList(addresses)); logger.info(logBuffer.toString()); recipients.clear(); return true; } catch (SendFailedException sfe) { if (sfe.getValidSentAddresses() != null) { Address[] validSent = sfe.getValidSentAddresses(); if (validSent.length > 0) { logBuffer = new StringBuilder(256).append("Successfully sent message to host ") .append(outgoingMailServer.getHostName()).append(" at ") .append(outgoingMailServer.getHost()).append(" for addresses ") .append(Arrays.asList(validSent)); logger.info(logBuffer.toString()); // Remove the addresses to which this message was // sent successfully List<InternetAddress> temp = new ArrayList<InternetAddress>(); for (int i = 0; i < addresses.length; i++) { if (!ArrayUtils.contains(validSent, addresses[i])) { if (addresses[i] != null) { temp.add(addresses[i]); } } } addresses = temp.toArray(new InternetAddress[temp.size()]); removeAll(recipients, validSent); } } if (sfe instanceof SMTPSendFailedException) { SMTPSendFailedException ssfe = (SMTPSendFailedException) sfe; // If permanent error 5xx, terminate this delivery // attempt by re-throwing the exception if (ssfe.getReturnCode() >= 500 && ssfe.getReturnCode() <= 599) throw sfe; } if (!ArrayUtils.isEmpty(sfe.getValidUnsentAddresses())) { // Valid addresses remained, so continue with any other server. if (logger.isDebugEnabled()) logger.debug("Send failed, " + sfe.getValidUnsentAddresses().length + " valid recipients(" + Arrays.asList(sfe.getValidUnsentAddresses()) + ") remain, continuing with any other servers"); lastError = sfe; continue; } else { // There are no valid addresses left to send, so re-throw throw sfe; } } catch (MessagingException me) { Exception ne; if ((ne = me.getNextException()) != null && ne instanceof IOException) { // It can be some socket or weird I/O related problem. lastError = me; continue; } throw me; } } // end while if (lastError != null) { throw lastError; } } catch (SendFailedException sfe) { boolean deleteMessage = false; if (sfe instanceof SMTPSendFailedException) { SMTPSendFailedException ssfe = (SMTPSendFailedException) sfe; deleteMessage = (ssfe.getReturnCode() >= 500 && ssfe.getReturnCode() <= 599); } else { // Sometimes we'll get a normal SendFailedException with nested // SMTPAddressFailedException, so use the latter RetCode MessagingException me = sfe; Exception ne; while ((ne = me.getNextException()) != null && ne instanceof MessagingException) { me = (MessagingException) ne; if (me instanceof SMTPAddressFailedException) { SMTPAddressFailedException ssfe = (SMTPAddressFailedException) me; deleteMessage = (ssfe.getReturnCode() >= 500 && ssfe.getReturnCode() <= 599); } } } if (!ArrayUtils.isEmpty(sfe.getInvalidAddresses())) { // Invalid addresses should be considered permanent Address[] invalid = sfe.getInvalidAddresses(); removeAll(recipients, invalid); deleteMessage = failMessage(message, invalid, sfe, true); } if (!ArrayUtils.isEmpty(sfe.getValidUnsentAddresses())) { // Vaild-unsent addresses should be considered temporary deleteMessage = failMessage(message, sfe.getValidUnsentAddresses(), sfe, false); } return deleteMessage; } catch (MessagingException mex) { // Check whether this is a permanent error (like account doesn't // exist or mailbox is full or domain is setup wrong) // We fail permanently if this was 5xx error. return failMessage(message, addresses, mex, ('5' == mex.getMessage().charAt(0))); } // If we get here, we've exhausted the loop of servers without sending // the message or throwing an exception. // One case where this might happen is if there is no server we can // connect. So this should be considered temporary return failMessage(message, addresses, new MessagingException("No mail server(s) available at this time."), false); }
From source file:com.midori.confluence.plugin.mail2news.Mail2NewsJob.java
/** * Send an mail containing the error message back to the * user which sent the given message.//from ww w . j a v a 2 s .c o m * * @param m The message which produced an error while handling it. * @param error The error string. */ private void sendErrorMessage(Message m, String error) throws Exception { /* get the SMTP mail server */ SMTPMailServer smtpMailServer = MailFactory.getServerManager().getDefaultSMTPMailServer(); if (smtpMailServer == null) { log.warn("Failed to send error message as no SMTP server is configured"); return; } /* get system properties */ Properties props = System.getProperties(); /* Setup mail server */ props.put("mail.smtp.host", smtpMailServer.getHostname()); /* get a session */ Session session = Session.getDefaultInstance(props, null); /* create the message */ MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(smtpMailServer.getDefaultFrom())); String senderEmail = getEmailAddressFromMessage(m); if (senderEmail == "") { throw new Exception("Unknown sender of email."); } message.addRecipient(Message.RecipientType.TO, new InternetAddress(senderEmail)); message.setSubject("[mail2news] Error while handling message (" + m.getSubject() + ")"); message.setText("An error occurred while handling your message:\n\n " + error + "\n\nPlease contact the administrator to solve the problem.\n"); /* send the message */ Transport tr = session.getTransport("smtp"); if (StringUtils.isBlank(smtpMailServer.getSmtpPort())) { tr.connect(smtpMailServer.getHostname(), smtpMailServer.getUsername(), smtpMailServer.getPassword()); } else { int smtpPort = Integer.parseInt(smtpMailServer.getSmtpPort()); tr.connect(smtpMailServer.getHostname(), smtpPort, smtpMailServer.getUsername(), smtpMailServer.getPassword()); } message.saveChanges(); tr.sendMessage(message, message.getAllRecipients()); tr.close(); }
From source file:com.panet.imeta.trans.steps.mail.Mail.java
public void sendMail(Object[] r, String server, String port, String senderAddress, String senderName, String destination, String destinationCc, String destinationBCc, String contactPerson, String contactPhone, String authenticationUser, String authenticationPassword, String mailsubject, String comment, String replyToAddresses) throws Exception { // Send an e-mail... // create some properties and get the default Session String protocol = "smtp"; if (meta.isUsingAuthentication()) { if (meta.getSecureConnectionType().equals("TLS")) { // Allow TLS authentication data.props.put("mail.smtp.starttls.enable", "true"); } else {/* ww w . ja v a2s.c om*/ protocol = "smtps"; // required to get rid of a SSL exception : // nested exception is: // javax.net.ssl.SSLException: Unsupported record version Unknown data.props.put("mail.smtps.quitwait", "false"); } } data.props.put("mail." + protocol + ".host", server); if (!Const.isEmpty(port)) data.props.put("mail." + protocol + ".port", port); boolean debug = log.getLogLevel() >= LogWriter.LOG_LEVEL_DEBUG; if (debug) data.props.put("mail.debug", "true"); if (meta.isUsingAuthentication()) data.props.put("mail." + protocol + ".auth", "true"); Session session = Session.getInstance(data.props); session.setDebug(debug); // create a message Message msg = new MimeMessage(session); // set message priority if (meta.isUsePriority()) { String priority_int = "1"; if (meta.getPriority().equals("low")) priority_int = "3"; if (meta.getPriority().equals("normal")) priority_int = "2"; msg.setHeader("X-Priority", priority_int); //(String)int between 1= high and 3 = low. msg.setHeader("Importance", meta.getImportance()); //seems to be needed for MS Outlook. //where it returns a string of high /normal /low. } // set Email sender String email_address = senderAddress; if (!Const.isEmpty(email_address)) { // get sender name if (!Const.isEmpty(senderName)) email_address = senderName + '<' + email_address + '>'; msg.setFrom(new InternetAddress(email_address)); } else { throw new MessagingException(Messages.getString("Mail.Error.ReplyEmailNotFilled")); } // Set reply to if (!Const.isEmpty(replyToAddresses)) { // get replay to // Split the mail-address: space separated String[] reply_Address_List = replyToAddresses.split(" "); InternetAddress[] address = new InternetAddress[reply_Address_List.length]; for (int i = 0; i < reply_Address_List.length; i++) address[i] = new InternetAddress(reply_Address_List[i]); // To add the real reply-to msg.setReplyTo(address); } // Split the mail-address: space separated String destinations[] = destination.split(" "); InternetAddress[] address = new InternetAddress[destinations.length]; for (int i = 0; i < destinations.length; i++) address[i] = new InternetAddress(destinations[i]); msg.setRecipients(Message.RecipientType.TO, address); String realdestinationCc = destinationCc; if (!Const.isEmpty(realdestinationCc)) { // Split the mail-address Cc: space separated String destinationsCc[] = realdestinationCc.split(" "); InternetAddress[] addressCc = new InternetAddress[destinationsCc.length]; for (int i = 0; i < destinationsCc.length; i++) addressCc[i] = new InternetAddress(destinationsCc[i]); msg.setRecipients(Message.RecipientType.CC, addressCc); } String realdestinationBCc = destinationBCc; if (!Const.isEmpty(realdestinationBCc)) { // Split the mail-address BCc: space separated String destinationsBCc[] = realdestinationBCc.split(" "); InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length]; for (int i = 0; i < destinationsBCc.length; i++) addressBCc[i] = new InternetAddress(destinationsBCc[i]); msg.setRecipients(Message.RecipientType.BCC, addressBCc); } if (mailsubject != null) msg.setSubject(mailsubject); msg.setSentDate(new Date()); StringBuffer messageText = new StringBuffer(); if (comment != null) messageText.append(comment).append(Const.CR).append(Const.CR); if (meta.getIncludeDate()) messageText.append(Messages.getString("Mail.Log.Comment.MsgDate") + ": ") .append(XMLHandler.date2string(new Date())).append(Const.CR).append(Const.CR); if (!meta.isOnlySendComment() && (!Const.isEmpty(contactPerson) || !Const.isEmpty(contactPhone))) { messageText.append(Messages.getString("Mail.Log.Comment.ContactInfo") + " :").append(Const.CR); messageText.append("---------------------").append(Const.CR); messageText.append(Messages.getString("Mail.Log.Comment.PersonToContact") + " : ").append(contactPerson) .append(Const.CR); messageText.append(Messages.getString("Mail.Log.Comment.Tel") + " : ").append(contactPhone) .append(Const.CR); messageText.append(Const.CR); } data.parts = new MimeMultipart(); MimeBodyPart part1 = new MimeBodyPart(); // put the text in the // 1st part if (meta.isUseHTML()) { if (!Const.isEmpty(meta.getEncoding())) part1.setContent(messageText.toString(), "text/html; " + "charset=" + meta.getEncoding()); else part1.setContent(messageText.toString(), "text/html; " + "charset=ISO-8859-1"); } else part1.setText(messageText.toString()); data.parts.addBodyPart(part1); // attached files if (meta.isDynamicFilename()) setAttachedFilesList(r, log); else setAttachedFilesList(null, log); msg.setContent(data.parts); Transport transport = null; try { transport = session.getTransport(protocol); if (meta.isUsingAuthentication()) { if (!Const.isEmpty(port)) { transport.connect(Const.NVL(server, ""), Integer.parseInt(Const.NVL(port, "")), Const.NVL(authenticationUser, ""), Const.NVL(authenticationPassword, "")); } else { transport.connect(Const.NVL(server, ""), Const.NVL(authenticationUser, ""), Const.NVL(authenticationPassword, "")); } } else { transport.connect(); } transport.sendMessage(msg, msg.getAllRecipients()); } finally { if (transport != null) transport.close(); } }