【问题标题】:How to send email in Java from Xpages?如何从 Xpages 用 Ja​​va 发送电子邮件?
【发布时间】:2018-09-15 14:29:15
【问题描述】:

在我的 Xpages 应用程序中,我想从 Java 发送 (HTML) 电子邮件。我在 OpenNTF 上发现了这个不错的 EmailBean 代码作为 sn-p:

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

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

我还想以不同的方式使用代码:我不想使用从 XPage 创建的 DominoDocument,而是想直接使用来自 anotehr 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 是预期的,而 Document 不例外。

我的下一个想法是在哪里跳过中间文档的创建但是当我尝试时

email.setBodyHTML("Hello World");

我在控制台中收到以下消息:

[1728:0016-08FC] 2018-09-15 16:18:14 HTTP JVM:不允许使用方法 setBodyHTML(string)

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

【问题讨论】:

    标签: java xpages html-email


    【解决方案1】:

    在 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() 方法中,不是从文档中提取,而是使用局部变量

    这对你有用吗?

    【讨论】:

    • 您的意思是通过文档(而不是 DominoDocument)
    【解决方案2】:

    为什么不去掉那个电子邮件类?

    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);
            }
        }
    

    DominoDocument 不再被读取。我添加了一个字段: private String bodyHTML 。我已将 setBodyHTML 方法更改为标准的 setter 方法。

    我剥离的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 电子邮件,没有图片或附件。我不确定这是否符合您的需求?

    【讨论】:

    • 谢谢帕特里克,我使用了你的代码,现在我可以发送电子邮件了!
    【解决方案3】:

    我对 OpenNTF Domino API 进行了相同的转换过程。它有一个DominoEmail 类,请参阅https://stash.openntf.org/projects/ODA/repos/dominoapi/browse/domino/core/src/org/openntf/domino/email?at=30690a2ddccb024bae6fcf37cbdd42860c7e5ba6。这适用于基本电子邮件,包括我相信的 HTML。但它对于支持例如并不完整。附件。如果有特定需求,我很高兴有人能够完成这方面的工作,并乐于提供建议以帮助取得进展。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-16
      • 2011-11-14
      • 2016-12-12
      • 2011-03-09
      • 1970-01-01
      • 2013-11-28
      • 1970-01-01
      相关资源
      最近更新 更多