hi,guys:
    i have create a new control named JavaMail Control,it can help
you to sending email. but now i can not parse method parameter when
dealing my annotation like jdbc controls  do(for example: wo can use
{a.b} in sql annotation).so i contribute it to beehive,perhaps you can
upgrade it to be another system control release in next version of
beehive.
    all source code,examples and test cases is provided in attachment.
    if you have questions,think it for free to mail me.
/**
 * JavaMailControl.java
 * 2005-10-10/16:18:25 created by King Xiao
 * 
 * @author King Xiao
 * beehive examples powered By www.vivianj.org
 */
package org.vivianj.beehive.controls.examples.javamail;

import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.apache.beehive.controls.api.bean.AnnotationConstraints;
import org.apache.beehive.controls.api.bean.AnnotationMemberTypes;
import org.apache.beehive.controls.api.bean.ControlInterface;
import org.apache.beehive.controls.api.properties.PropertySet;

/**
 *  The control interface for the JavaMail control.
 */
@ControlInterface
public interface JavaMailControl {

        /**
         * Returns the last exception serviced by the JavaMail control on the
     * developers behalf.  This can be used to discover or log additional
     * information, for example when your mail is not send successfully.
         */
        public Throwable getMailException();

        /**
         * SMTPServer specifies the environment properties for the smtp server.
         * 
         */
        @PropertySet(prefix = "SMTPServer")
        @Inherited
        @AnnotationConstraints.AllowExternalOverride
        @Retention(RetentionPolicy.RUNTIME)
        @Target( { ElementType.TYPE, ElementType.FIELD })
        public @interface SMTPServer {

                /**
                 * The address of SMTP server
                 */
                String serverAddress();

                /**
                 * specifies we must provider security or not when we use smtp 
to send emails.
                 */
                @AnnotationMemberTypes.Optional
                boolean authorizationRequired() default false;

                /**
         * A String containing the user name to connect to the smtp server. 
Optional element.
         */
                @AnnotationMemberTypes.Optional
                String principal() default "";

                /**
         * A String containing the passwor to connect to the smtp server. 
Optional element.
         */
                @AnnotationMemberTypes.Optional
                String credentials() default "";
        }
        
        /**
         * 
         * Message specifies the environment properties for email.
         */
        @PropertySet(prefix = "Message")
        @Inherited
        @AnnotationConstraints.AllowExternalOverride
        @Retention(RetentionPolicy.RUNTIME)
        @Target( { ElementType.METHOD })
        public @interface Message {

                /**
                 * The sender of mail.
                 */
                String from();
                
                /**
                 * The "To" (primary) recipients of mail.
                 */
                String to();
                
                /**
                 * The "Cc" (carbon copy) recipients of mail.
                 */
                @AnnotationMemberTypes.Optional
                String cc() default "";
                
                /**
                 * The "Bcc" (blind carbon copy) recipients of mail.
                 */
                @AnnotationMemberTypes.Optional
                String bcc() default "";
                
                /**
                 * subject of mail.
                 */
                @AnnotationMemberTypes.Optional
                String subject() default "";
                
                /**
                 * content type of mail.
                 */
                @AnnotationMemberTypes.Optional
                String contentType() default "text/plain;charset=UTF-8";
        

                /**
                 * The attachment recipients of mail.
                 */
                @AnnotationMemberTypes.Optional
                String attachment() default "";

        }
}
/**
 * JavaMailControlImpl.java
 * 2005-10-10/16:20:16 created by King Xiao
 * 
 * @author King Xiao
 * beehive examples powered By www.vivianj.org
 */
package org.vivianj.beehive.controls.examples.javamail;

import java.lang.reflect.Method;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.beehive.controls.api.bean.ControlImplementation;
import org.apache.beehive.controls.api.bean.Extensible;
import org.apache.beehive.controls.api.context.Context;
import org.apache.beehive.controls.api.context.ControlBeanContext;
import org.apache.beehive.controls.api.context.ResourceContext;
import org.apache.beehive.controls.api.context.ControlBeanContext.LifeCycle;
import org.apache.beehive.controls.api.events.EventHandler;

/**
 * The implementation class for the JavaMail control.
 */
@ControlImplementation
public class JavaMailControlImpl implements JavaMailControl, Extensible,
                java.io.Serializable {

        static final long serialVersionUID = 1L;

        @Context
        ControlBeanContext context;

        @Context
        ResourceContext resourceContext;

        private Throwable lastException;

        private Session session;

        private Properties props;

        private String serverAddress;

        private boolean authorizationRequired;

        private String principal;

        private String credentials;

        private MimeMessage mimeMessage;

        private Multipart multipart;

        @EventHandler(field = "context", eventSet = LifeCycle.class, eventName 
= "onCreate")
        public void onCreate() {
                SMTPServer server = (SMTPServer) context
                                .getControlPropertySet(SMTPServer.class);

                serverAddress = server.serverAddress();

                authorizationRequired = server.authorizationRequired();
                principal = server.principal();
                credentials = server.credentials();

                if (props == null)
                        props = System.getProperties();

                props.put("mail.smtp.host", serverAddress);
                setAuthorizationRequired(authorizationRequired);
        }

        public Throwable getMailException() {

                return lastException;
        }


        public Object invoke(Method m, Object[] args) throws Throwable {
                Message message = (Message) context.getMethodPropertySet(m,
                                Message.class);
                String to = message.to();
                String from = message.from();
                String cc = message.cc();
                String bcc = message.bcc();
                String contentType = message.contentType();
                String attachment = message.attachment();
                String subject = message.subject();
                Object body = null;
                if (args.length < 1) {
                        body = "";
                        throw new IllegalArgumentException(
                                        "At most one parameter may be defined 
as the body of the Mail message");
                } else
                        body = args[0];
                createMimeMessage();
                setFrom(from);
                setTo(to);
                setCC(cc);
                setBCC(bcc);
                setSubject(subject);
                setBody(body, contentType);
                setAttachment(attachment);

                sendMail();
                return null;
        }

        /**
         * Set the authorization pattern of smtp server.
         * 
         * @param need
         *            authorization pattern of smtp server,true or false
         */
        private void setAuthorizationRequired(boolean need) {
                if (props == null)
                        props = System.getProperties();

                if (need) {
                        props.put("mail.smtp.auth", "true");
                } else {
                        props.put("mail.smtp.auth", "false");
                }
        }

        /**
         * create MimeMessage
         */
        private void createMimeMessage() throws Exception {
                try {
                        /* get mail sessoin */
                        session = Session.getDefaultInstance(props, null);
                } catch (Exception e) {
                        e.printStackTrace();
                        lastException = e;
                        throw e;
                }
                try {
                        mimeMessage = new MimeMessage(session);
                        multipart = new MimeMultipart();
                } catch (Exception e) {
                        e.printStackTrace();
                        lastException = e;
                        throw e;
                }
        }

        /**
         * Set the body of mail
         * 
         * @param body
         *            body of mail
         * @param contentType
         *            content type of mail
         */
        public void setBody(Object body, String contentType) throws Exception {
                try {
                        BodyPart bodyPart = new MimeBodyPart();
                        bodyPart.setContent(body, contentType);
                        multipart.addBodyPart(bodyPart);

                } catch (Exception e) {
                        e.printStackTrace();
                        lastException = e;
                        throw e;
                }
        }

        /**
         * Set the subject of mail.
         * 
         * @param subject
         *            the subject of mail.
         */
        public void setSubject(String subject) throws Exception {
                try {
                        mimeMessage.setSubject(subject);

                } catch (Exception e) {
                        e.printStackTrace();
                        lastException = e;
                        throw e;
                }
        }

        /**
         * set attachment of mail
         * 
         * @param attachment
         *            file path of attachment
         */
        public void setAttachment(String attachment) throws Exception {

                try {
                        BodyPart bp = new MimeBodyPart();
                        FileDataSource fileds = new FileDataSource(attachment);
                        bp.setDataHandler(new DataHandler(fileds));
                        bp.setFileName(fileds.getName());

                        multipart.addBodyPart(bp);
                } catch (Exception e) {
                        e.printStackTrace();
                        lastException = e;
                        throw e;
                }
        }

        /**
         * Set the sender of mail.
         * 
         * @param from
         *            the sender of mail.
         */
        public void setFrom(String from) throws Exception {
                try {
                        mimeMessage.setFrom(new InternetAddress(from));
                } catch (Exception e) {
                        e.printStackTrace();
                        lastException = e;
                        throw e;
                }
        }

        /**
         * Set the "To" (primary) recipients of mail.
         * 
         * @param to
         *            the "To" (primary) recipients of mail.
         */
        public void setTo(String to) throws Exception {
                try {
                        
mimeMessage.setRecipients(javax.mail.Message.RecipientType.TO,
                                        InternetAddress.parse(to));
                } catch (Exception e) {
                        e.printStackTrace();
                        lastException = e;
                        throw e;
                }

        }

        /**
         * Set the "Cc" (carbon copy) recipients of mail.
         * 
         * @param cc
         *            the "Cc" (carbon copy) recipients of mail.
         */
        public void setCC(String cc) throws Exception {
                try {
                        
mimeMessage.setRecipients(javax.mail.Message.RecipientType.CC,
                                        (Address[]) InternetAddress.parse(cc));
                } catch (Exception e) {
                        e.printStackTrace();
                        lastException = e;
                        throw e;
                }
        }

        /**
         * Set the "Bcc" (blind carbon copy) recipients of mail.
         * 
         * @param bcc
         *            the "Bcc" (blind carbon copy) recipients of mail.
         */
        public void setBCC(String bcc) throws Exception {
                try {
                        
mimeMessage.setRecipients(javax.mail.Message.RecipientType.BCC,
                                        (Address[]) InternetAddress.parse(bcc));
                } catch (Exception e) {
                        e.printStackTrace();
                        lastException = e;
                        throw e;
                }
        }

        /**
         * send mail
         * 
         */
        private void sendMail() throws Exception {
                try {
                        mimeMessage.setContent(multipart);
                        mimeMessage.saveChanges();

                        Session mailSession = Session.getInstance(props, null);
                        
                        Transport transport = mailSession.getTransport("smtp");
                        if (authorizationRequired)
                                transport.connect((String) 
props.get("mail.smtp.host"),
                                                principal, credentials);
                        else
                                transport.connect((String) 
props.get("mail.smtp.host"), "", "");

                        
                        /* send email to all "To" (primary) recipients of mail 
*/
                        Address[] tos = mimeMessage
                                        
.getRecipients(javax.mail.Message.RecipientType.TO);
                        if (tos != null && tos.length > 0) {
                                System.out.println("tos.length = " + 
tos.length);

                                transport.sendMessage(mimeMessage, tos);
                        }
                        /* send email to all "Cc" (carbon copy) recipients of 
mail. */
                        Address[] ccs = mimeMessage
                                        
.getRecipients(javax.mail.Message.RecipientType.CC);

                        if (ccs != null && ccs.length > 0) {
                                transport.sendMessage(mimeMessage, ccs);
                                System.out.println("ccs.length = " + 
ccs.length);
                        }
                        /* send email to all "Bcc" (blind carbon copy) 
recipients of mail. */
                        Address[] bccs = mimeMessage
                                        
.getRecipients(javax.mail.Message.RecipientType.BCC);

                        if (bccs != null && bccs.length > 0) {
                                transport.sendMessage(mimeMessage, bccs);
                                System.out.println("bccs.length = " + 
bccs.length);
                        }

                        /* close connection with smtp server */
                        transport.close();

                } catch (Exception e) {
                        e.printStackTrace();
                        lastException = e;
                        throw e;
                }
        }
}
/**
 * VivianjJavaMailControlTest.java
 * 2005-10-11/23:52:22 created by King Xiao
 * 
 * @author King Xiao
 * beehive examples powered By www.vivianj.org
 */
package org.vivianj.beehive.controls.examples.unittest;

import org.apache.beehive.controls.api.bean.Control;
import org.apache.beehive.test.tools.milton.junit.MiltonTestCase;
import org.vivianj.beehive.controls.examples.VivianjJavaMailControlBean;

public class VivianjJavaMailControlTest extends MiltonTestCase {
        /* ʹÓÃÉùÃ÷ʽ¿Ø¼þʵÀý»¯·½Ê½ÊµÀý»¯JavaMail¿Ø¼þ */
        @Control
        public VivianjJavaMailControlBean _bean;

        public VivianjJavaMailControlTest(String name) throws Exception {
                super(name);
        }

        public void testSendMail() {
                /* µ÷ÓÿؼþµÄsendMail·½·¨Íê³ÉÓʼþ·¢ËÍ */
                _bean.sendMail("body");
        }
}
/**
 * VivianjJavaMailCotrol.java
 * 2005-10-10/17:16:18 created by King Xiao
 * 
 * @author King Xiao
 * beehive examples powered By www.vivianj.org
 */
package org.vivianj.beehive.controls.examples;

import org.apache.beehive.controls.api.bean.ControlExtension;
import org.vivianj.beehive.controls.examples.javamail.JavaMailControl;

/**
 * VivianjJavaMailControl ÓÃÓڼ̳ÐJavaMail¿Ø¼þ<br>
 * ʵÏÖʹÓÃsmtp.163.comÓʼþ·þÎñÆ÷·¢ËÍÓʼþµÄ¹¦ÄÜ<br>
 * ʹÓøÃSMTP·þÎñÆ÷ÐèÒªÌṩ°²È«ÐÅÏ¢
 */
@ControlExtension
@JavaMailControl.SMTPServer(serverAddress = "mail.vivianj.org", 
authorizationRequired = false)
public interface VivianjJavaMailControl extends JavaMailControl {

        /**
         * Íê³É·¢ËÍÓʼþµÄ¹¦ÄÜ<br>
         * [EMAIL PROTECTED]<br>
         * [EMAIL PROTECTED]<br>
         * ÓʼþÖ÷ÌâÊÇhello<br>
         * ÓʼþµÄÄÚÈÝÓɿؼþʹÓÃÕßÔÚµ÷ÓÃʱʹÓòÎÊýbody´«Èë<br>
         * 
         * @param body
         *            ÓʼþµÄÄÚÈÝ
         */
        @JavaMailControl.Message(from = "[EMAIL PROTECTED]", to = "[EMAIL 
PROTECTED]", subject = "subject")
        public void sendMail(String body);
}

Reply via email to