⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 smtpclient.java

📁 java开源的企业总线.xmlBlaster
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
               ErrorCode.RESOURCE_CONFIGURATION_ADDRESS, "SmtpClient",               "Your URI '" + this.xbUri.toString() +               "' is illegal, expecting something like 'smtp://user:password@host:port'");      }            props.put("mail.user", this.xbUri.getUser());      if (this.xbUri.getPassword() != null) {         //props.put("mail.password", this.xbUri.getPassword()); // I don't think "mail.password" is ever used, remove again?         props.setProperty("mail.smtp.auth", "true"); //Indicate that authentication is required at smtp server      }      props.put("mail.transport.protocol", this.xbUri.getScheme());      props.put("mail.smtp.host", this.xbUri.getHost());      if (this.xbUri.getPort() > 0)         props.put("mail.smtp.port", ""+this.xbUri.getPort());            String p;      if (props.getProperty("messageIdForceBase64") == null)         props.put("messageIdForceBase64", ""+glob.get("messageIdForceBase64", false, null,               pluginConfig));      p = props.getProperty("messageIdForceBase64");      this.messageIdForceBase64 = new Boolean(p).booleanValue();            if (props.getProperty("contentForceBase64") == null)         props.put("contentForceBase64", ""+glob.get("contentForceBase64", false, null,               pluginConfig));      p = props.getProperty("contentForceBase64");      this.contentForceBase64 = new Boolean(p).booleanValue();      if (props.getProperty("addExpiresHeader") == null)         props.put("addExpiresHeader", ""+glob.get("addExpiresHeader", true, null,               pluginConfig));      p = props.getProperty("addExpiresHeader");      this.addExpiresHeader = new Boolean(p).booleanValue();            if (props.getProperty("breakLongMessageIdLine") == null)         props.put("breakLongMessageIdLine", ""+glob.get("breakLongMessageIdLine", false, null,               pluginConfig));      p = props.getProperty("breakLongMessageIdLine");      this.breakLongMessageIdLine = new Boolean(p).booleanValue();      if (props.getProperty("inlineExtension") == null)         props.put("inlineExtension", ""+glob.get("inlineExtension", "", null,               pluginConfig));      this.inlineExtension = props.getProperty("inlineExtension"); // like ".txt,.xml"            if (props.getProperty("mail.smtp.timeout") == null)          props.put("mail.smtp.timeout", ""+glob.get("mail.smtp.timeout",        		  Integer.MAX_VALUE, null,                pluginConfig));       p = props.getProperty("mail.smtp.timeout");       this.smtpIoTimeout = new Integer(p).intValue();       if (props.getProperty("mail.smtp.connectiontimeout") == null)           props.put("mail.smtp.connectiontimeout", ""+glob.get("mail.smtp.connectiontimeout",         		  Integer.MAX_VALUE, null,                 pluginConfig));        p = props.getProperty("mail.smtp.connectiontimeout");        this.smtpConnectionTimeout = new Integer(p).intValue();      // Pass "this" for SMTP authentication with Authenticator      this.authentication = new PasswordAuthentication(getUser(), this.xbUri.getPassword());      this.session = Session.getDefaultInstance(props, this);      this.isInitialized = true;            if (this.mbeanHandle == null) {        // For JMX instanceName may not contain ","        this.contextNode = new ContextNode(ContextNode.SERVICE_MARKER_TAG,                            "SmtpClient[" + getType() + "]",                             glob.getScopeContextNode());        this.mbeanHandle = glob.registerMBean(this.contextNode, this);      }      log.info("SMTP client to '" + this.xbUri.getUrlWithoutPassword() + "' is ready");   }   /**    * Access the mailing session.    */   public Session getSession() {      return this.session;   }   public Message getMessage() {      return new MimeMessage(getSession());   }   /**    * Send a ready prepared message.    * <p>    * Usually you choose the convenience method sendEmail()    * </p>    */   public void send(Message message) throws MessagingException {/* * Reuse transport for better performance: * See http://java.sun.com/products/javamail/FAQ.html  MimeMessage msg = ...;   construct message   msg.saveChanges();   Transport t = session.getTransport("smtp");   t.connect();   for (int i = 0; .....) {     t.sendMessage(msg, new Address[] { recipients[i] });   }   t.close();*/      try {         Transport.send(message);      } catch (MessagingException e) {         throw e;      }   }   public void sendEmail(String from, String to, String subject, String body)         throws AddressException, MessagingException {      Message message = getMessage();      try {         message.setFrom(new InternetAddress(from));         InternetAddress tos[] = new InternetAddress[1];         tos[0] = new InternetAddress(to);         message.setRecipients(Message.RecipientType.TO, tos);         message.setSubject(subject);         message.setContent(body, "text/plain");      } catch (MessagingException e) {         throw e;      }      send(message);   }   public void sendEmail(String from, String to, String subject, String body,         String encoding) throws AddressException, MessagingException {      sendEmail(new InternetAddress(from), new InternetAddress(to), subject,            body, encoding);   }   /**    * @param body    *           Is assumed to be of mime type "text/plain"    * @param encoding    *           (charset) for example "UTF-8", will set the mail header:    *     * <pre>    *          Content-Type: text/plain; charset=UTF-8    * </pre>    */   public void sendEmail(InternetAddress from, InternetAddress to,         String subject, String body, String encoding) throws AddressException,         MessagingException {      MimeMessage message = new MimeMessage(getSession());      try {         message.setFrom(from);         InternetAddress tos[] = new InternetAddress[1];         tos[0] = to;         message.setRecipients(Message.RecipientType.TO, tos);         message.setSubject(subject, encoding);         message.setText(body, encoding); // is automatically "text/plain"      } catch (MessagingException e) {         throw e;      }      send(message);   }   /**    * @param attachmentName2    *           If not null this second attachment is added as "text/plain"    * @param encoding    *           For example "UTF-8"    */   public void sendEmail(InternetAddress from, InternetAddress to,         String subject, String attachmentName, byte[] attachment,         String attachmentName2, String attachment2, String encoding)         throws XmlBlasterException {      try {         MimeMessage message = new MimeMessage(getSession());         message.setFrom(from);         InternetAddress tos[] = new InternetAddress[1];         tos[0] = to;         message.setRecipients(Message.RecipientType.TO, tos);         message.setSubject(subject, encoding);         // MimeBodyPart mbp1 = new MimeBodyPart(attachment);         MimeBodyPart mbp1 = new MimeBodyPart(); // "application/x-any"         // "application/xmlBlaster-xbformat"         DataSource ds = new ByteArrayDataSource(attachment,               "application/xmlBlaster-xbformat");         mbp1.setDataHandler(new DataHandler(ds));         mbp1.setFileName(attachmentName);         // mbp1.getContentType(); "application/octet-stream"         // create the Multipart and add its parts to it         Multipart mp = new MimeMultipart();         mp.addBodyPart(mbp1);         if (attachmentName2 != null) {            MimeBodyPart mbp2 = new MimeBodyPart(); // "text/plain"            mbp2.setText(attachment2, encoding);            mbp2.setFileName(attachmentName2);            mp.addBodyPart(mbp2);         }         // add the Multipart to the message         message.setContent(mp);         // set the Date: header         message.setSentDate(new Date());         // message.setContent("A test mail from xmlBlaster with attachment in         // xmlBlaster-SOCKET format", encoding); // is automatically         // "text/plain"         send(message);         if (log.isLoggable(Level.FINE))            log.fine("Successful send email from=" + from.toString() + " to="                  + to.toString());      } catch (Exception e) {         throw new XmlBlasterException(Global.instance(),               ErrorCode.COMMUNICATION_NOCONNECTION, "SmtpClient",               "Email sending failed, no mail sent to " + to.toString(), e);      }   }      /**    * JMX    */   public String sendTestEmail(String to, String from) {      if (to==null || to.trim().length() < 1 || "String".equalsIgnoreCase(to)) to = "demo@localhost";      if (from==null || from.trim().length() < 1 || "String".equalsIgnoreCase(from)) from = "xmlBlaster@localhost";      EmailData emailData = new EmailData(to, from, "[xmlBlaster SmtpClient] Test email", "Hello world!");      try {         sendEmail(emailData);      } catch (XmlBlasterException e) {         e.printStackTrace();         throw new IllegalArgumentException(e.toString());      }      return "Send email from '" + from + "' to '" + to + "'";   }   /**    * Send a mail.    * @param emailData    *        Container holding the message to send    */   public void sendEmail(EmailData emailData) throws XmlBlasterException {      if (emailData == null) throw new IllegalArgumentException("SmtpClient.sendEmail(): Missing argument emailData");      try {         MimeMessage message = new MimeMessage(getSession());         message.setFrom(emailData.getFromAddress());         message.setRecipients(Message.RecipientType.TO, emailData.getToAddresses());         if (emailData.getCc().length > 0)            message.setRecipients(Message.RecipientType.CC, emailData.getCc());         if (emailData.getBcc().length > 0)            message.setRecipients(Message.RecipientType.BCC, emailData.getBcc());         message.setSubject(emailData.getSubject(), Constants.UTF8_ENCODING);         AttachmentHolder[] holder = emailData.getAttachments();         if (holder.length == 0 && emailData.getContent() != null && emailData.getContent().length() > 0) {            message.setText(emailData.getContent(), Constants.UTF8_ENCODING);         }         else {            // create the Multipart and add its parts to it            Multipart multi = new MimeMultipart();               if (emailData.getContent() != null && emailData.getContent().length() > 0) {               MimeBodyPart mbp = new MimeBodyPart();               mbp.setFileName("content.txt");               mbp.setText(emailData.getContent(), Constants.UTF8_ENCODING);               mbp.setDisposition(MimeBodyPart.INLINE);               multi.addBodyPart(mbp);            }               for (int i=0; i<holder.length; i++) {               MimeBodyPart mbp = new MimeBodyPart();               // 'AA xmlBlasterMessage.xbf' will be automatically quoted to '"AA xmlBlasterMessage.xbf"' by javamail implementation               // 'xx.xbf' names will be send unquoted               mbp.setFileName(holder[i].getFileName());               byte[] content = holder[i].getContent();               if (this.messageIdForceBase64 && emailData.isMessageIdAttachment(holder[i])                    || this.contentForceBase64 && emailData.isMsgUnitAttachment(holder[i])) {                  //We don't need to do it, javamail does it for us                  //content = Base64.encode(holder[i].getContent()).getBytes(Constants.UTF8_ENCODING);                  //Buggy: is not accepted by javamail: (Why? and How?)                  mbp.setHeader(Constants.EMAIL_TRANSFER_ENCODING, Constants.ENCODING_BASE64);  // "Content-Transfer-Encoding", "base64");               }               else {                  // http://www.ietf.org/rfc/rfc2045.txt                  // The Quoted-Printable encoding REQUIRES that encoded lines be no more than 76                  // characters long. (78 with CRLF), the line uses a trailing '=' as a soft line brake                  mbp.setHeader(Constants.EMAIL_TRANSFER_ENCODING, Constants.ENCODING_QUOTED_PRINTABLE);  // "Content-Transfer-Encoding", "quoted-printable");

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -