代码之家  ›  专栏  ›  技术社区  ›  Malin

如何从Xpages用Java发送电子邮件?

  •  0
  • Malin  · 技术社区  · 6 年前

    在我的Xpages应用程序中,我想从Java发送(HTML)电子邮件。我在OpenNTF上发现了这个漂亮的EmailBean代码片段:

    https://openntf.org/XSnippets.nsf/snippet.xsp?id=emailbean-send-dominodocument-html-emails-cw-embedded-images-attachments-custom-headerfooter

    我将代码转换为一个公共电子邮件类,而不是将其用作托管bean。

    我还想以另一种方式使用代码:与使用从XPage创建的DominoDocument不同,我想直接使用另一个java类中的类。但我面临以下问题:

    代码需要一个DominoDocument和该文档上的一个字段作为电子邮件的内容。

    所以在我的sendMail方法中我尝试了:

    Database db = DominoUtils.getCurrentDatabase();
    DominoDocument fakeMail = (DominoDocument) db.createDocument();
    

    但是这个DominoDocument从未创建过(代码在这里中断)

    Database db = DominoUtils.getCurrentDatabase();
    Document fakeMail = db.createDocument();
    

    很好,但是

    Email email = new Email();
    email.setDocument(fakeMail);
    

    投诉需要DominoDocument,但文档不例外。

    email.setBodyHTML("Hello World");
    

    控制台中显示以下消息:

    有没有人可以指导我如何更改电子邮件类,这样我就不需要DominoDocument了?实际上我根本不需要文件。如果setBodyHTML()可以工作,我可以自己设置email对象的属性。

    3 回复  |  直到 6 年前
        1
  •  1
  •   Patrick Kwinten    6 年前

    为什么不把邮件类去掉呢?

    package com.ibm.xsp.utils;
    
    /**
     * @author Tony McGuckin, IBM
     */
    
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.regex.Pattern;
    
    import lotus.domino.Database;
    import lotus.domino.Document;
    import lotus.domino.MIMEEntity;
    import lotus.domino.MIMEHeader;
    import lotus.domino.NotesException;
    import lotus.domino.Session;
    import lotus.domino.Stream;
    
    import com.ibm.domino.xsp.module.nsf.NotesContext;
    
    public class Email {
    
        private ArrayList<String> sendTo;
          private ArrayList<String> ccList;
          private ArrayList<String> bccList;
          private String senderEmail;
          private String senderName;
          private String subject;
          private String fieldName;
          private String bannerHTML;
          private String bodyHTML;
          private String footerHTML;
    
          private boolean debugMode = true;
    
          private static final Pattern imgRegExp = Pattern.compile("<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>");
    
          public Email(){
                this.subject = "";
                this.sendTo = new ArrayList<String>();
                this.ccList = new ArrayList<String>();
                this.bccList = new ArrayList<String>();
          }
    
          public String getSendTo(){
            if(this.isDebugMode()){
              System.out.println("getSendTo() : " + this.sendTo.toString());
            }
            return this.sendTo.toString().replace("[", "").replace("]", "");
          }
    
          public void setSendTo(final String sendTo){
            this.sendTo.add(sendTo);
          }
    
          public String getCcList(){
            if(this.isDebugMode()){
              System.out.println("getCcList() : " + this.ccList.toString());
            }
            return this.ccList.toString().replace("[", "").replace("]", "");
          }
    
          public void setCcList(final String ccList){
            this.ccList.add(ccList);
          }
    
          public String getBccList(){
            if(this.isDebugMode()){
              System.out.println("getBccList() : " + this.bccList.toString());
            }
            return this.bccList.toString().replace("[", "").replace("]", "");
          }
    
          public void setBccList(final String bccList){
            this.bccList.add(bccList);
          }
    
          public String getSenderEmail(){
            return this.senderEmail;
          }
    
          public void setSenderEmail(final String senderEmail){
            this.senderEmail = senderEmail;
          }
    
          public String getSenderName(){
            return this.senderName;
          }
    
          public void setSenderName(final String senderName){
            this.senderName = senderName;
          }
    
          public String getSubject(){
            return this.subject;
          }
    
          public void setSubject(final String subject){
            this.subject = subject;
          }
    
          public boolean isDebugMode(){
            return this.debugMode;
          }
    
          public void setDebugMode(final boolean debugMode){
            this.debugMode = debugMode;
          }
    
          private Session getCurrentSession(){
            NotesContext nc = NotesContext.getCurrentUnchecked();
              return (null != nc) ? nc.getCurrentSession() : null;
          }
    
          private Database getCurrentDatabase(){
            NotesContext nc = NotesContext.getCurrentUnchecked();
              return (null != nc) ? nc.getCurrentDatabase() : null;
          }
    
          public void send() throws NotesException, IOException, Exception {
                Session session = getCurrentSession();
                Database database = getCurrentDatabase();
                if (null != session && null != database &&
                    null != this.sendTo && null != this.subject &&
                    null != this.senderEmail
                ) {
                    try {
                        if (this.isDebugMode()) {
                            System.out.println("Started send()");
                        }
                        session.setConvertMime(false);
                        Document emailDocument = database.createDocument();
    
                        MIMEEntity emailRoot = emailDocument.createMIMEEntity("Body");
                        if (null != emailRoot) {
                            MIMEHeader emailHeader = emailRoot.createHeader("Reply-To");
                            emailHeader.setHeaderVal(this.getSenderEmail());
    
                            emailHeader = emailRoot.createHeader("Return-Path");
                            emailHeader.setHeaderVal(this.getSenderEmail());
    
                            final String fromSender = (null == this.getSenderName()) ?
                                this.getSenderEmail() :
                                "\"" + this.getSenderName() + "\" <" + this.getSenderEmail() + ">";
    
                            emailHeader = emailRoot.createHeader("From");
                            emailHeader.setHeaderVal(fromSender);
    
                            emailHeader = emailRoot.createHeader("Sender");
                            emailHeader.setHeaderVal(fromSender);
    
                            emailHeader = emailRoot.createHeader("To");
                            emailHeader.setHeaderVal(this.getSendTo());
    
                            if (!this.ccList.isEmpty()) {
                                emailHeader = emailRoot.createHeader("CC");
                                emailHeader.setHeaderVal(this.getCcList());
                            }
    
                            if (!this.bccList.isEmpty()) {
                                emailHeader = emailRoot.createHeader("BCC");
                                emailHeader.setHeaderVal(this.getBccList());
                            }
    
                            emailHeader = emailRoot.createHeader("Subject");
                            emailHeader.setHeaderVal(this.getSubject());
    
                            MIMEEntity emailRootChild = emailRoot.createChildEntity();
                            if (null != emailRootChild) {
                                final String boundary = System.currentTimeMillis() + "-" + "ABC";
                                emailHeader = emailRootChild.createHeader("Content-Type");
                                emailHeader.setHeaderVal("multipart/alternative; boundary=\"" + boundary + "\"");
    
                                MIMEEntity emailChild = emailRootChild.createChildEntity();
                                if (null != emailChild) {
    
                                    Stream stream = session.createStream();                             
    
                                    emailChild = emailRootChild.createChildEntity();
                                    stream = session.createStream();
                                    stream.writeText(this.getHTML());
                                    emailChild.setContentFromText(stream, "text/html; charset=\"UTF-8\"", MIMEEntity.ENC_NONE);
                                    stream.close();
                                    stream.recycle();
                                    stream = null;
                                }                   
                            }
                        }
                        emailDocument.send();
                        session.setConvertMime(true);
                        if (this.isDebugMode()) {
                            System.out.println("Completed send()");
                        }
                    } catch (NotesException e) {
                        if (this.isDebugMode()) {
                            System.out.println("Failed send() with NotesException" + e.getMessage());
                        }
                        throw e;
                    }  catch (Exception e) {
                        if (this.isDebugMode()) {
                            System.out.println("Failed send() with Exception" + e.getMessage());
                        }
                        throw e;
                    }
                }
            }
    
          public String getFieldName(){
            return this.fieldName;
          }
    
          public void setFieldName(final String fieldName){
            this.fieldName = fieldName;
          }
    
          public String getHTML(){
            StringBuffer html = new StringBuffer();
            html.append(getBannerHTML());
            html.append(getBodyHTML());
            html.append(getFooterHTML());
            return html.toString();
          }
    
          public String getBannerHTML(){
            return this.bannerHTML;
          }
    
          public void setBannerHTML(final String bannerHTML){
            this.bannerHTML = bannerHTML;
          }
    
          public String getFooterHTML(){
            return this.footerHTML;
          }
    
          public String getBodyHTML() {
            return bodyHTML;
        }
    
        public void setBodyHTML(String bodyHTML) {
            this.bodyHTML = bodyHTML;
        }
    
        public void setFooterHTML(final String footerHTML){
            this.footerHTML = footerHTML;
        }      
    
    }
    

    然后从你的另一个类中添加如下内容:

    private void sendMail(String msg){
            try{            
                Email email = new Email();          
                email.setSendTo("yourname@acme.org");
                email.setSubject("Mail from Java");         
                email.setSenderEmail("no-rely@acme.org");           
                email.setSenderName("No-reply");            
                email.setBodyHTML(msg);             
                email.setBannerHTML("<p>Hi " + email.getSendTo() + ",</p>");            
                email.setFooterHTML("<p><b>Kind regards,</b><br/>" + email.getSenderName() + "<br/>0044 1234 5678</p>");
                email.send();           
            } catch (Exception e) {
                OpenLogUtil.logError(e);
            }
        }
    

    我剥离的send()方法,主要是这一部分:

    MIMEEntity emailRootChild = emailRoot.createChildEntity();
                            if (null != emailRootChild) {
                                final String boundary = System.currentTimeMillis() + "-" + "ABC";
                                emailHeader = emailRootChild.createHeader("Content-Type");
                                emailHeader.setHeaderVal("multipart/alternative; boundary=\"" + boundary + "\"");
    
                                MIMEEntity emailChild = emailRootChild.createChildEntity();
                                if (null != emailChild) {
    
                                    Stream stream = session.createStream();                             
    
                                    emailChild = emailRootChild.createChildEntity();
                                    stream = session.createStream();
                                    stream.writeText(this.getHTML());
                                    emailChild.setContentFromText(stream, "text/html; charset=\"UTF-8\"", MIMEEntity.ENC_NONE);
                                    stream.close();
                                    stream.recycle();
                                    stream = null;
                                }                   
                            }
    

    最后你只得到一个基本的HTML电子邮件,没有图像或附件。我不确定这是否符合你的需要?

        2
  •  2
  •   stwissel    6 年前

    在Domino中发送邮件的方法是通过文档。最简单的方法是在 mail.box ,路由器数据库。在那里,您只能保存一次,保存将发送消息。

    托尼的课应该很好,没有你提到的任何转换工作。托管bean只是一个简单的Java类,具有无参数构造函数和get/set方法。

    因此,从其他Java代码中,您应该能够使用以下内容:

    EmailBean email = new EmailBean();
    email.set(...) // to, body, subject etc
    email.send();
    

    您需要更改的内容:

    • get/setHTMLBody 需要像HTMLfooter一样工作->存储在局部变量中
    • get/setTextBody 方法与局部变量
    • send()

    对你有用吗?

        3
  •  0
  •   Paul Stephen Withers    6 年前

    对于OpenNTF dominoapi,我经历了相同的转换过程。它有一个 DominoEmail https://stash.openntf.org/projects/ODA/repos/dominoapi/browse/domino/core/src/org/openntf/domino/email?at=30690a2ddccb024bae6fcf37cbdd42860c7e5ba6 . 这适用于基本的电子邮件,包括HTML我相信。但它并不完全支持附件等。我很高兴有人能够完成这方面的工作,如果有具体的需要,并乐意提供建议,以帮助进步。