跟大家分享我寫的一小段Groovy代碼,可以用來通過Gmail的SMTP服務發送郵件。Dependancy只需JavaMail。
/** Send e-mail by GMail. */ def sendMail(user, pw, recipients, subject, body) { Security.addProvider new com.sun.net.ssl.internal.ssl.Provider() def props = System.properties props.'mail.smtp.host' = 'smtp.gmail.com' props.'mail.smtp.socketFactory.class' = 'javax.net.ssl.SSLSocketFactory' props.'mail.smtp.socketFactory.fallback' = 'false' props.'mail.smtp.port' = '465' props.'mail.smtp.socketFactory.port' = '465' props.'mail.smtp.auth' = 'true' // This can only be compiled in Groovy 1.7, the anonymous inner class def session = javax.mail.Session.getDefaultInstance(props, new javax.mail.Authenticator() { javax.mail.PasswordAuthentication getPasswordAuthentication() { new javax.mail.PasswordAuthentication(user, pw) } }) def msg = new javax.mail.internet.MimeMessage(session) msg.setFrom new javax.mail.internet.InternetAddress(user + '@gmail.com') msg.setRecipients javax.mail.Message.RecipientType.TO, javax.mail.internet.InternetAddress.parse(recipients, false) msg.setSubject subject msg.setText body msg.setSentDate new Date() try { javax.mail.Transport.send msg // success } catch (Exception e) { // failed } }