Mailer.java 14.4 KB
Newer Older
K
kohsuke 已提交
1 2 3
package hudson.tasks;

import hudson.Launcher;
4
import hudson.Functions;
5
import hudson.maven.AbstractMavenProject;
K
kohsuke 已提交
6 7 8 9 10 11 12
import hudson.model.AbstractProject;
import hudson.model.Build;
import hudson.model.BuildListener;
import hudson.model.Descriptor;
import hudson.model.Project;
import hudson.model.User;
import hudson.model.UserPropertyDescriptor;
J
jbq 已提交
13
import hudson.util.FormFieldValidator;
K
kohsuke 已提交
14 15 16 17 18
import org.apache.tools.ant.types.selectors.SelectorUtils;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
K
kohsuke 已提交
19

J
jbq 已提交
20
import javax.mail.Authenticator;
21 22
import javax.mail.Message;
import javax.mail.MessagingException;
J
jbq 已提交
23 24
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
25
import javax.mail.Transport;
J
jbq 已提交
26 27
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
28
import javax.mail.internet.MimeMessage;
J
jbq 已提交
29
import javax.servlet.ServletException;
K
kohsuke 已提交
30 31 32 33 34 35 36 37
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Date;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
J
jbq 已提交
38

K
kohsuke 已提交
39
/**
40
 * {@link Publisher} that sends the build result in e-mail.
K
kohsuke 已提交
41 42 43 44
 *
 * @author Kohsuke Kawaguchi
 */
public class Mailer extends Publisher {
45
    protected static final Logger LOGGER = Logger.getLogger(Mailer.class.getName());
K
kohsuke 已提交
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67

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

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

    public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();

107
    public static final class DescriptorImpl extends BuildStepDescriptor<Publisher> {
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
        /**
         * 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 已提交
126
         * Null if not configured.
127 128 129 130 131 132 133 134
         */
        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 已提交
135 136 137 138 139
        
        /**
         * If true use SSL on port 465 (standard SMTPS).
         */
        private boolean useSsl;
140 141 142 143 144

        /**
         * Used to keep track of number test e-mails.
         */
        private static transient int testEmailCount = 0;
K
kohsuke 已提交
145
        
K
kohsuke 已提交
146 147 148

        public DescriptorImpl() {
            super(Mailer.class);
149
            load();
K
kohsuke 已提交
150 151
        }

152 153 154 155 156 157 158 159 160 161 162 163
        /**
         * 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 已提交
164
        public String getDisplayName() {
K
i18n  
kohsuke 已提交
165
            return Messages.Mailer_DisplayName();
K
kohsuke 已提交
166 167 168 169 170 171 172
        }

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

        public String getDefaultSuffix() {
173
            return defaultSuffix;
K
kohsuke 已提交
174 175 176 177 178
        }

        /** JavaMail session. */
        public Session createSession() {
            Properties props = new Properties(System.getProperties());
179 180
            if(smtpHost!=null)
                props.put("mail.smtp.host",smtpHost);
K
kohsuke 已提交
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
            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.
            	 */
            	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");
			}
197 198
            if(getSmtpAuthUserName()!=null)
                props.put("mail.smtp.auth","true");
K
kohsuke 已提交
199 200 201 202 203 204 205 206 207 208 209 210 211
            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());
                }
            };
        }

212
        public boolean configure(StaplerRequest req) throws FormException {
K
kohsuke 已提交
213
            // this code is brain dead
214 215
            smtpHost = nullify(req.getParameter("mailer_smtp_server"));
            adminAddress = req.getParameter("mailer_admin_address");
216 217 218 219 220 221
            if(adminAddress.startsWith("\"") && adminAddress.endsWith("\"")) {
                // some users apparently quote the whole thing. Don't konw why
                // anyone does this, but it's a machine's job to forgive human mistake
                adminAddress = adminAddress.substring(1,adminAddress.length()-1);
            }

222
            defaultSuffix = nullify(req.getParameter("mailer_default_suffix"));
K
kohsuke 已提交
223 224 225
            String url = nullify(req.getParameter("mailer_hudson_url"));
            if(url!=null && !url.endsWith("/"))
                url += '/';
226
            hudsonUrl = url;
K
kohsuke 已提交
227

228 229 230 231 232 233
            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 已提交
234
            useSsl = req.getParameter("mailer_smtp_use_ssl")!=null;
K
kohsuke 已提交
235 236 237 238 239 240 241 242 243 244
            save();
            return super.configure(req);
        }

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

        public String getSmtpServer() {
245
            return smtpHost;
K
kohsuke 已提交
246 247 248
        }

        public String getAdminAddress() {
249
            String v = adminAddress;
250
            if(v==null)     v = "address not configured yet <nobody@nowhere>";
K
kohsuke 已提交
251 252 253 254
            return v;
        }

        public String getUrl() {
255
            return hudsonUrl;
K
kohsuke 已提交
256 257 258
        }

        public String getSmtpAuthUserName() {
259
            return smtpAuthUsername;
K
kohsuke 已提交
260 261 262
        }

        public String getSmtpAuthPassword() {
263
            return smtpAuthPassword;
K
kohsuke 已提交
264
        }
K
kohsuke 已提交
265 266 267 268
        
        public boolean getUseSsl() {
        	return useSsl;
        }
K
kohsuke 已提交
269 270 271 272

        public Publisher newInstance(StaplerRequest req) {
            Mailer m = new Mailer();
            req.bindParameters(m,"mailer_");
K
kohsuke 已提交
273
            m.dontNotifyEveryUnstableBuild = req.getParameter("mailer_notifyEveryUnstableBuild")==null;
274 275 276 277 278 279 280

            if(hudsonUrl==null) {
                // if Hudson URL is not configured yet, infer some default
                hudsonUrl = Functions.inferHudsonURL(req);
                save();
            }

K
kohsuke 已提交
281 282
            return m;
        }
K
kohsuke 已提交
283 284 285 286 287 288 289 290 291 292 293 294 295 296

        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();
        }
297 298 299 300 301 302 303 304 305 306 307 308 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
        
        /**
         * Send an email to the admin address
         * @param req ignored request
         * @param rsp used to write the result of the sending
         * @throws IOException
         * @throws ServletException
         * @throws InterruptedException
         */
        public void doSendTestMail(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, InterruptedException {
            rsp.setContentType("text/plain");
            PrintStream writer = new PrintStream(rsp.getOutputStream());            
            try {
                writer.println("Sending email to " + getAdminAddress());
                writer.println();
                writer.println("Email content ---------------------------------------------------------");
                writer.flush();
                
                MimeMessage msg = new MimeMessage(createSession());
                msg.setSubject("Test email #" + ++testEmailCount);
                msg.setContent("This is test email #" + testEmailCount + " sent from Hudson Continuous Integration server.", "text/plain");
                msg.setFrom(new InternetAddress(getAdminAddress()));
                msg.setSentDate(new Date());
                msg.setRecipient(Message.RecipientType.TO, new InternetAddress(getAdminAddress()));                
                msg.writeTo(writer);
                writer.println();                
                writer.println("-----------------------------------------------------------------------");
                writer.println();
                writer.flush();
                
                Transport.send(msg);
                
                writer.println("Email was successfully sent");
            } catch (MessagingException e) {
                writer.println(e.getMessage());
            }
            writer.flush();
        }
335 336 337 338 339

        public boolean isApplicable(Class<? extends AbstractProject> jobType) {
            // for historical reasons, Maven uses MavenMailer
            return !AbstractMavenProject.class.isAssignableFrom(jobType);
        }
K
kohsuke 已提交
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
    }

    /**
     * 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;
        }

358
        @Exported
K
kohsuke 已提交
359 360 361 362
        public String getAddress() {
            if(emailAddress!=null)
                return emailAddress;

K
bug fix  
kohsuke 已提交
363
            // try the inference logic
K
kohsuke 已提交
364
            return MailAddressResolver.resolve(user);
K
kohsuke 已提交
365 366 367 368 369 370 371 372 373 374 375 376
        }

        public DescriptorImpl getDescriptor() {
            return DESCRIPTOR;
        }

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

            public String getDisplayName() {
K
i18n  
kohsuke 已提交
377
                return Messages.Mailer_UserProperty_DisplayName();
K
kohsuke 已提交
378 379 380
            }

            public UserProperty newInstance(User user) {
381
                
K
bug fix  
kohsuke 已提交
382
                return new UserProperty(null);
K
kohsuke 已提交
383 384 385 386 387 388 389
            }

            public UserProperty newInstance(StaplerRequest req) throws FormException {
                return new UserProperty(req.getParameter("email.address"));
            }
        }
    }
K
kohsuke 已提交
390 391 392 393

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