77. Lotus Notes中编程发送邮件(三)之XPages中用Java发送邮件

46. LotusNotes中编程发送邮件(一)47.Lotus Notes中编程发送邮件(二)里笔者介绍了在Lotus Notes发送邮件的几种简单场景和需求,并给出了以LotusScript编写的通用代码。本文介绍可在XPages开发时使用的一个用于发送邮件的Java类,具备LotusScript代码的所有功能,且有更友好方便的API。

这个类具备如下功能:

  • 发送Notes邮件。
  • 发送HTML邮件。
  • 设置抄送和盲送。
  • 设置显示的发件人(发送HTML邮件时无效)。
  • 设置回邮件的地址。

具有以下特点:

  • 使用简单,方便。对最普通的发送邮件的情况只需两行代码。可根据情况灵活设置抄送、盲送、显示的发件人和回邮件的地址等多个属性。每个设置属性的方法都返回该邮件类的当前实例,使得可以进行简洁的链式调用。
  • 参数灵活。按照Notes邮件文档对应各收件人的文本域可接受的数据类型,设定各收件人时,既可使用单个的字符串,也可用代表多人的Vector<String>。
  • 使用安全。对设定的各收件人都进行了参数校验,确保可以被邮件文档的文本域接受。

我们先来看使用这个邮件类的示例,代码是一个被XPage调用的managed bean的方法:

	public void testMail(){
		String sendTo="admin";
		String body="hello";
		try {
			//一封简单的Notes邮件,和下面的各种邮件一道,收件人使用的都是Notes用户名作地址。
			Mail mail=new Mail(sendTo, "A simple Notes mail", body);
			mail.send();
			//一封有各种收件人的简单的Notes邮件
			mail=new Mail(sendTo, "User1", "User2", "A Notes mail with all types of receivers", body);
			mail.send();
			//一封设置了抄送和回邮件的地址的Notes邮件
			mail=new Mail(sendTo, "A Notes mail with some receivers and replyTo set using Mail's methods", body);
			mail.setCopyTo("User1").setReplyTo("ServiceDesk").send();
			//一封设置了显示的发件人的HTML邮件
			mail=new Mail(sendTo, "A HTML mail", "<h1>Hello</h1>");
			mail.setPrincipal("ServiceDesk").send();
			
		} catch (Exception e) {
			XSPUtil.feedback(e.getMessage());
		}
	}

下面是这个邮件类的代码,如果要在普通的Java代理里使用,只需改写Session对象的来源。

package starrow.xsp;

import java.util.Vector;

import starrow.AppException;

import lotus.domino.Database;
import lotus.domino.Directory;
import lotus.domino.Document;
import lotus.domino.MIMEEntity;
import lotus.domino.NotesException;
import lotus.domino.RichTextItem;
import lotus.domino.Session;
import lotus.domino.Stream;

@SuppressWarnings("unchecked")
public class Mail {
    private Session session;
    private Database db;
    private Document memo;
    private String domain=""; //Notes domain
    private Object sendTo;
    private String subject="";
    private String body="";
    private Document docLink=null;
    private Object copyTo="";
    private Object blindCopyTo="";
    private String replyTo="";
    private String principal="";
    
    
    /**
     * Only set the fields. Put all the Notes related actions in the buildMail method to avoid NotesException in constructs.
     * @param sendTo provide String or Vector<String> value to set the Notes text item. 
     * @param copyTo provide String or Vector<String> value to set the Notes text item.
     * @param blindCopyTo provide String or Vector<String> value to set the Notes text item.
     * @param subject String value
     * @param body can be HTML in case of sending HTML mails.
     * @throws NotesException
     */
    public Mail(Object sendTo, Object copyTo, Object blindCopyTo, String subject, String body){
        this.setSendTo(sendTo);
        this.setCopyTo(copyTo);
        this.setBlindCopyTo(blindCopyTo);
        this.subject=subject;
        this.body=body;
    }

    public Mail(Object sendTo, String subject, String body){
        this(sendTo, "", "", subject, body);
    }

    /**
     * Check and set the sendTo field.
     * @param sendTo String or Vector of Strings
     * @return the current instance for the convenience of method chaining.
     */
    private Mail setSendTo(Object sendTo){
        if (!Mail.isTextValues(sendTo)){
            throw new IllegalArgumentException("sendTo should be a String or Vector<String>.");
        }
        this.sendTo=sendTo;
        return this;
    }
    
    /**
     * Check and set the copyTo field.
     * @param copyTo String or Vector of Strings
     * @return the current instance for the convenience of method chaining.
     */
    public Mail setCopyTo(Object copyTo){
        if (!Mail.isTextValues(copyTo)){
            throw new IllegalArgumentException("copyTo should be a String or Vector<String>.");
        }
        this.copyTo=copyTo;
        return this;
    }
    
    /**
     * Check and set the blindCopyTo field.
     * @param blindCopyTo String or Vector of Strings
     * @return the current instance for the convenience of method chaining.
     */    
    public Mail setBlindCopyTo(Object blindCopyTo){
        if (!Mail.isTextValues(blindCopyTo)){
            throw new IllegalArgumentException("blindCopyTo should be a String or Vector<String>.");
        }
        this.blindCopyTo=blindCopyTo;
        return this;        
    }
    
    public Mail setReplyTo(String replyTo){
        this.replyTo=replyTo;
        return this;
    }
    
    public Mail setPrincipal(String principal){
        this.principal=principal;
        return this;
    }
    
    public Mail setDocLink(Document doc){
        this.docLink=doc;
        return this;
    }

    private void buildMail() throws NotesException{
        session = XSPUtil.getSession();
        db = session.getCurrentDatabase();
        memo = db.createDocument();
        memo.replaceItemValue("Form", "memo");

        memo.replaceItemValue("SendTo",sendTo);
        memo.replaceItemValue("CopyTo", copyTo);
        memo.replaceItemValue("BlindCopyTo", blindCopyTo);
        memo.replaceItemValue("Subject",subject);
        // Principal overrides From
        // Must be formatted as below and must include the Domino domain
        //memo.Principal = |"Customer Service" <starrow@mail.com@DominoDomain>|
        if ( ! this.replyTo.equals("")) {
            this.getDomain();
            memo.replaceItemValue("ReplyTo", this.replyTo + "@" + this.domain);
        }

        if ( ! this.principal.equals("")) {
            this.getDomain();
            memo.replaceItemValue("Principal" ,this.principal + "@" + this.domain);
        }
    }
    
    public static boolean isTextValues(Object value){
        //Notes text items accept values of String or Vector<String>
        //But cannot perform instanceof check against parameterized type Vector<String>. 
        //Use instead its raw form Vector since generic type information will be erased at runtime.
        if (value instanceof String){
            return true;
        }
        if (value instanceof Vector){
            Vector list=(Vector)value;
            if (list.get(0) instanceof String){
                return true;
            }
        }
            return false;        
    }
    
    private void getDomain() throws NotesException {
        if ( ! this.domain.equals("")) {
            return;
        }
        Directory nd = session.getDirectory(session.getServerName());
        Vector info = nd.getMailInfo(session.getEffectiveUserName());
        this.domain=(String) info.get(5);
    }

    /*
    public void copyItem(Item item, String itemName) throws NotesException {
        memo.copyItem(item, itemName);
    }
    */

    public void send() throws AppException{
        try{
            this.buildMail();
            RichTextItem bodyItem=memo.createRichTextItem("Body");
            bodyItem.appendText(body);
            if (docLink != null) {
                bodyItem.appendDocLink(docLink,"click the link");
            }

            memo.send();
        }catch(Exception e){
            throw new AppException(e.getMessage());
        }
    }
    
    /**
     * Setting principal has no effect on a HTML mail.
     * @throws AppException
     */
    public void sendHTMLMail() throws AppException {
        try {
            this.buildMail();
            session.setConvertMIME(false);
            Stream stream = session.createStream();
            stream.writeText(body);
            MIMEEntity entity = memo.createMIMEEntity("Body");
            entity.setContentFromText(stream,"text/html;charset=UTF-8", 1725);
            stream.close();
            memo.send(false);
            session.setConvertMIME(true);
        } catch (Exception e) {
            throw new AppException(e.getMessage());
        }
    }

}
  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值