通過Gmail發送郵件的Groovy腳本

跟大家分享我寫的一小段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
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值