FileDocCategorySizeDatePackage
MimeMailer.javaAPI DocApache Ant 1.7010394Wed Dec 13 06:16:20 GMT 2006org.apache.tools.ant.taskdefs.email

MimeMailer

public class MimeMailer extends Mailer
Uses the JavaMail classes to send Mime format email.
since
Ant 1.5

Fields Summary
private static final String
SSL_FACTORY
private static final String
DEFAULT_CHARSET
Default character set
Constructors Summary
Methods Summary
private static javax.mail.internet.InternetAddress[]internetAddresses(java.util.Vector list)

        InternetAddress[] addrs = new InternetAddress[list.size()];

        for (int i = 0; i < list.size(); ++i) {
            EmailAddress addr = (EmailAddress) list.elementAt(i);

            String name = addr.getName();
            addrs[i] = (name == null)
                ? new InternetAddress(addr.getAddress())
                : new InternetAddress(addr.getAddress(), name);
        }
        return addrs;
    
private java.lang.StringparseCharSetFromMimeType(java.lang.String type)

        int pos;
        if (type == null || (pos = type.indexOf("charset")) < 0) {
          return null;
        }
        // Assuming mime type in form "text/XXXX; charset=XXXXXX"
        StringTokenizer token = new StringTokenizer(type.substring(pos), "=; ");
        token.nextToken(); // Skip 'charset='
        return token.nextToken();
    
public voidsend()
Send the email.

throws
BuildException if the email can't be sent.

        try {
            Properties props = new Properties();

            props.put("mail.smtp.host", host);
            props.put("mail.smtp.port", String.valueOf(port));

            // Aside, the JDK is clearly unaware of the Scottish
            // 'session', which involves excessive quantities of
            // alcohol :-)
            Session sesh;
            Authenticator auth;
            if (SSL) {
                try {
                    Provider p = (Provider) Class.forName(
                        "com.sun.net.ssl.internal.ssl.Provider").newInstance();
                    Security.addProvider(p);
                } catch (Exception e) {
                    throw new BuildException("could not instantiate ssl "
                        + "security provider, check that you have JSSE in "
                        + "your classpath");
                }
                // SMTP provider
                props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
                props.put("mail.smtp.socketFactory.fallback", "false");
            }
            if (user == null && password == null) {
                sesh = Session.getDefaultInstance(props, null);
            } else {
                props.put("mail.smtp.auth", "true");
                auth = new SimpleAuthenticator(user, password);
                sesh = Session.getInstance(props, auth);
            }
            //create the message
            MimeMessage msg = new MimeMessage(sesh);
            MimeMultipart attachments = new MimeMultipart();

            //set the sender
            if (from.getName() == null) {
                msg.setFrom(new InternetAddress(from.getAddress()));
            } else {
                msg.setFrom(new InternetAddress(from.getAddress(),
                    from.getName()));
            }
            // set the reply to addresses
            msg.setReplyTo(internetAddresses(replyToList));
            msg.setRecipients(Message.RecipientType.TO,
                internetAddresses(toList));
            msg.setRecipients(Message.RecipientType.CC,
                internetAddresses(ccList));
            msg.setRecipients(Message.RecipientType.BCC,
                internetAddresses(bccList));

            // Choosing character set of the mail message
            // First: looking it from MimeType
            String charset = parseCharSetFromMimeType(message.getMimeType());
            if (charset != null) {
                // Assign/reassign message charset from MimeType
                message.setCharset(charset);
            } else {
                // Next: looking if charset having explicit definition
                charset = message.getCharset();
                if (charset == null) {
                    // Using default
                    charset = DEFAULT_CHARSET;
                    message.setCharset(charset);
                }
            }
            // Using javax.activation.DataSource paradigm
            StringDataSource sds = new StringDataSource();
            sds.setContentType(message.getMimeType());
            sds.setCharset(charset);

            if (subject != null) {
                msg.setSubject(subject, charset);
            }
            msg.addHeader("Date", getDate());

            for (Iterator iter = headers.iterator(); iter.hasNext();) {
                Header h = (Header) iter.next();
                msg.addHeader(h.getName(), h.getValue());
            }
            PrintStream out = new PrintStream(sds.getOutputStream());
            message.print(out);
            out.close();

            MimeBodyPart textbody = new MimeBodyPart();
            textbody.setDataHandler(new DataHandler(sds));
            attachments.addBodyPart(textbody);

            Enumeration e = files.elements();

            while (e.hasMoreElements()) {
                File file = (File) e.nextElement();

                MimeBodyPart body;

                body = new MimeBodyPart();
                if (!file.exists() || !file.canRead()) {
                    throw new BuildException("File \"" + file.getAbsolutePath()
                         + "\" does not exist or is not "
                         + "readable.");
                }
                FileDataSource fileData = new FileDataSource(file);
                DataHandler fileDataHandler = new DataHandler(fileData);

                body.setDataHandler(fileDataHandler);
                body.setFileName(file.getName());
                attachments.addBodyPart(body);
            }
            msg.setContent(attachments);
            Transport.send(msg);
        } catch (MessagingException e) {
            throw new BuildException("Problem while sending mime mail:", e);
        } catch (IOException e) {
            throw new BuildException("Problem while sending mime mail:", e);
        }