Mailer.java 11.8 KB
Newer Older
K
kohsuke 已提交
1 2 3 4 5 6
package hudson.tasks;

import hudson.Launcher;
import hudson.model.Build;
import hudson.model.BuildListener;
import hudson.model.Descriptor;
7
import hudson.model.Project;
K
kohsuke 已提交
8 9
import hudson.model.User;
import hudson.model.UserPropertyDescriptor;
J
jbq 已提交
10
import hudson.util.FormFieldValidator;
K
kohsuke 已提交
11 12

import java.io.File;
K
kohsuke 已提交
13
import java.io.IOException;
K
kohsuke 已提交
14 15 16 17 18
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

J
jbq 已提交
19 20 21 22 23 24 25 26 27 28 29 30
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.servlet.ServletException;

import org.apache.tools.ant.types.selectors.SelectorUtils;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;

K
kohsuke 已提交
31
/**
32
 * {@link Publisher} that sends the build result in e-mail.
K
kohsuke 已提交
33 34 35 36 37 38
 *
 * @author Kohsuke Kawaguchi
 */
public class Mailer extends Publisher {
    private static final Logger LOGGER = Logger.getLogger(Mailer.class.getName());

J
jbq 已提交
39 40 41 42 43
    /**
     * @see #extractAddressFromId(String)
     */
    public static final String EMAIL_ADDRESS_REGEXP = "^.*<([^>]+)>.*$";

K
kohsuke 已提交
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
    /**
     * Whitespace-separated list of e-mail addresses that represent recipients.
     */
    public String recipients;

    /**
     * If true, only the first unstable build will be reported.
     */
    public boolean dontNotifyEveryUnstableBuild;

    /**
     * If true, individuals will receive e-mails regarding who broke the build.
     */
    public boolean sendToIndividuals;

    // TODO: left so that XStream won't get angry. figure out how to set the error handling behavior
    // in XStream.
    private transient String from;
    private transient String subject;
    private transient boolean failureOnly;

K
kohsuke 已提交
65
    public boolean perform(Build build, Launcher launcher, BuildListener listener) throws InterruptedException {
66 67 68 69
        return _perform(build,launcher,listener);
    }

    public <P extends Project<P,B>,B extends Build<P,B>> boolean _perform(B build, Launcher launcher, BuildListener listener) throws InterruptedException {
K
kohsuke 已提交
70 71
        if(debug)
            listener.getLogger().println("Running mailer");
72
        return new MailSender<P,B>(recipients,dontNotifyEveryUnstableBuild,sendToIndividuals) {
73 74
            /** Check whether a path (/-separated) will be archived. */
            @Override
75
            public boolean artifactMatches(String path, B build) {
76 77 78 79
                ArtifactArchiver aa = (ArtifactArchiver) build.getProject().getPublishers().get(ArtifactArchiver.DESCRIPTOR);
                if (aa == null) {
                    LOGGER.finer("No ArtifactArchiver found");
                    return false;
80
                }
81 82 83 84 85
                String artifacts = aa.getArtifacts();
                for (String include : artifacts.split("[, ]+")) {
                    String pattern = include.replace(File.separatorChar, '/');
                    if (pattern.endsWith("/")) {
                        pattern += "**";
K
kohsuke 已提交
86
                    }
87 88 89
                    if (SelectorUtils.matchPath(pattern, path)) {
                        LOGGER.log(Level.FINER, "DescriptorImpl.artifactMatches true for {0} against {1}", new Object[] {path, pattern});
                        return true;
K
kohsuke 已提交
90
                    }
K
kohsuke 已提交
91
                }
92 93
                LOGGER.log(Level.FINER, "DescriptorImpl.artifactMatches for {0} matched none of {1}", new Object[] {path, artifacts});
                return false;
K
kohsuke 已提交
94
            }
95
        }.execute(build,listener);
K
kohsuke 已提交
96 97 98 99 100 101 102 103 104
    }

    public Descriptor<Publisher> getDescriptor() {
        return DESCRIPTOR;
    }

    public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();

    public static final class DescriptorImpl extends Descriptor<Publisher> {
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
        /**
         * The default e-mail address suffix appended to the user name found from changelog,
         * to send e-mails. Null if not configured.
         */
        private String defaultSuffix;

        /**
         * Hudson's own URL, to put into the e-mail.
         */
        private String hudsonUrl;

        /**
         * If non-null, use SMTP-AUTH with these information.
         */
        private String smtpAuthPassword,smtpAuthUsername;

        /**
         * The e-mail address that Hudson puts to "From:" field in outgoing e-mails.
K
kohsuke 已提交
123
         * Null if not configured.
124 125 126 127 128 129 130 131
         */
        private String adminAddress;

        /**
         * The SMTP server to use for sending e-mail. Null for default to the environment,
         * which is usually <tt>localhost</tt>.
         */
        private String smtpHost;
K
kohsuke 已提交
132 133 134 135 136 137
        
        /**
         * If true use SSL on port 465 (standard SMTPS).
         */
        private boolean useSsl;
        
K
kohsuke 已提交
138 139 140

        public DescriptorImpl() {
            super(Mailer.class);
141
            load();
K
kohsuke 已提交
142 143
        }

144 145 146 147 148 149 150 151 152 153 154 155
        /**
         * For backward compatibility.
         */
        protected void convert(Map<String, Object> oldPropertyBag) {
            defaultSuffix = (String)oldPropertyBag.get("mail.default.suffix");
            hudsonUrl = (String)oldPropertyBag.get("mail.hudson.url");
            smtpAuthUsername = (String)oldPropertyBag.get("mail.hudson.smtpauth.username");
            smtpAuthPassword = (String)oldPropertyBag.get("mail.hudson.smtpauth.password");
            adminAddress = (String)oldPropertyBag.get("mail.admin.address");
            smtpHost = (String)oldPropertyBag.get("mail.smtp.host");
        }

K
kohsuke 已提交
156 157 158 159 160 161 162 163 164
        public String getDisplayName() {
            return "E-mail Notification";
        }

        public String getHelpFile() {
            return "/help/project-config/mailer.html";
        }

        public String getDefaultSuffix() {
165
            return defaultSuffix;
K
kohsuke 已提交
166 167 168 169 170
        }

        /** JavaMail session. */
        public Session createSession() {
            Properties props = new Properties(System.getProperties());
171 172
            if(smtpHost!=null)
                props.put("mail.smtp.host",smtpHost);
K
kohsuke 已提交
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
            if (useSsl) {
            	/* This allows the user to override settings by setting system properties but
            	 * also allows us to use the default SMTPs port of 465 if no port is already set.
            	 * It would be cleaner to use smtps, but that's done by calling session.getTransport()...
            	 * and thats done in mail sender, and it would be a bit of a hack to get it all to
            	 * coordinate, and we can make it work through setting mail.smtp properties.
            	 */
            	props.put("mail.smtp.auth","true");
            	if (props.getProperty("mail.smtp.socketFactory.port") == null) {
				    props.put("mail.smtp.port", "465");
    				props.put("mail.smtp.socketFactory.port", "465");
            	}
            	if (props.getProperty("mail.smtp.socketFactory.class") == null) {
            		props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
            	}
				props.put("mail.smtp.socketFactory.fallback", "false");
			}
K
kohsuke 已提交
190 191 192 193 194 195 196 197 198 199 200 201 202
            return Session.getInstance(props,getAuthenticator());
        }

        private Authenticator getAuthenticator() {
            final String un = getSmtpAuthUserName();
            if(un==null)    return null;
            return new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(getSmtpAuthUserName(),getSmtpAuthPassword());
                }
            };
        }

203
        public boolean configure(StaplerRequest req) throws FormException {
K
kohsuke 已提交
204
            // this code is brain dead
205 206 207
            smtpHost = nullify(req.getParameter("mailer_smtp_server"));
            adminAddress = req.getParameter("mailer_admin_address");
            defaultSuffix = nullify(req.getParameter("mailer_default_suffix"));
K
kohsuke 已提交
208 209 210
            String url = nullify(req.getParameter("mailer_hudson_url"));
            if(url!=null && !url.endsWith("/"))
                url += '/';
211
            hudsonUrl = url;
K
kohsuke 已提交
212

213 214 215 216 217 218
            if(req.getParameter("mailer.useSMTPAuth")!=null) {
                smtpAuthUsername = nullify(req.getParameter("mailer.SMTPAuth.userName"));
                smtpAuthPassword = nullify(req.getParameter("mailer.SMTPAuth.password"));
            } else {
                smtpAuthUsername = smtpAuthPassword = null;
            }
K
kohsuke 已提交
219
            useSsl = req.getParameter("mailer_smtp_use_ssl")!=null;
K
kohsuke 已提交
220 221 222 223 224 225 226 227 228 229
            save();
            return super.configure(req);
        }

        private String nullify(String v) {
            if(v!=null && v.length()==0)    v=null;
            return v;
        }

        public String getSmtpServer() {
230
            return smtpHost;
K
kohsuke 已提交
231 232 233
        }

        public String getAdminAddress() {
234
            String v = adminAddress;
K
kohsuke 已提交
235 236 237 238 239
            if(v==null)     v = "address not configured yet <nobody>";
            return v;
        }

        public String getUrl() {
240
            return hudsonUrl;
K
kohsuke 已提交
241 242 243
        }

        public String getSmtpAuthUserName() {
244
            return smtpAuthUsername;
K
kohsuke 已提交
245 246 247
        }

        public String getSmtpAuthPassword() {
248
            return smtpAuthPassword;
K
kohsuke 已提交
249
        }
K
kohsuke 已提交
250 251 252 253
        
        public boolean getUseSsl() {
        	return useSsl;
        }
K
kohsuke 已提交
254 255 256 257 258 259

        public Publisher newInstance(StaplerRequest req) {
            Mailer m = new Mailer();
            req.bindParameters(m,"mailer_");
            return m;
        }
K
kohsuke 已提交
260 261 262 263 264 265 266 267 268 269 270 271 272 273

        public void doAddressCheck(StaplerRequest req, StaplerResponse rsp,
                                   @QueryParameter("value") final String value) throws IOException, ServletException {
            new FormFieldValidator(req,rsp,false) {
                protected void check() throws IOException, ServletException {
                    try {
                        new InternetAddress(value);
                        ok();
                    } catch (AddressException e) {
                        error(e.getMessage());
                    }
                }
            }.process();
        }
K
kohsuke 已提交
274 275
    }

J
jbq 已提交
276 277 278 279 280 281 282 283 284
    /**
     * Tries to extract an email address from the user id, or returns null
     */
    public static String extractAddressFromId(String id) {
    	if (id.matches(EMAIL_ADDRESS_REGEXP))
    		return id.replaceFirst(EMAIL_ADDRESS_REGEXP, "$1");
    	return null;
    }

K
kohsuke 已提交
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
    /**
     * Per user property that is e-mail address.
     */
    public static class UserProperty extends hudson.model.UserProperty {
        public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();

        /**
         * The user's e-mail address.
         * Null to leave it to default.
         */
        private final String emailAddress;

        public UserProperty(String emailAddress) {
            this.emailAddress = emailAddress;
        }

        public String getAddress() {
            if(emailAddress!=null)
                return emailAddress;

J
jbq 已提交
305 306 307 308
        	String extractedAddress = extractAddressFromId(user.getId());
        	if (extractedAddress != null)
        		return extractedAddress;
            
K
kohsuke 已提交
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
            String ds = Mailer.DESCRIPTOR.getDefaultSuffix();
            if(ds!=null)
                return user.getId()+ds;
            else
                return null;
        }

        public DescriptorImpl getDescriptor() {
            return DESCRIPTOR;
        }

        public static final class DescriptorImpl extends UserPropertyDescriptor {
            public DescriptorImpl() {
                super(UserProperty.class);
            }

            public String getDisplayName() {
                return "E-mail";
            }

            public UserProperty newInstance(User user) {
                return new UserProperty(null);
            }

            public UserProperty newInstance(StaplerRequest req) throws FormException {
                return new UserProperty(req.getParameter("email.address"));
            }
        }
    }
K
kohsuke 已提交
338 339 340 341

    /**
     * Debug probe point to be activated by the scripting console.
     */
K
d'oh!  
kohsuke 已提交
342
    public static boolean debug = false;
K
kohsuke 已提交
343
}