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

问题描述 投票:0回答:3

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

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

我将代码转换为通用的Email类,而不是将其用作托管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
3个回答
1
投票

为什么不删除该电子邮件类?

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("[email protected]");
            email.setSubject("Mail from Java");         
            email.setSenderEmail("[email protected]");           
            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电子邮件,没有图像或附件。我不确定这是否符合您的需求?


2
投票

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

但是...... Tony的班级应该没有你提到的任何转换工作就可以正常工作。托管bean只是一个简单的Java类,带有参数自由构造函数和get / set方法。

所以从其他Java代码中你应该能够使用它:

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

你需要改变什么:

  • get/setHTMLBody需要像HTMLfooter一样工作 - >存储在局部变量中
  • 添加get/setTextBody方法和局部变量
  • send()方法中,而不是从文档中提取,使用局部变量

那对你有用吗?


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.