Last active
January 15, 2019 07:53
-
-
Save hatewx/d1e80e4c148dd30b8719c2c4dfdcff9c to your computer and use it in GitHub Desktop.
最简单 java/groovy 脚本,通过 SSL/TLS 的 SMTP 服务发送邮件
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import javax.mail.* | |
| import javax.mail.internet.* | |
| /** | |
| * 发送邮件 | |
| * @param addresser 发件人,与发件使用的账号可以不同 | |
| * @param password 发件账户账号密码 | |
| * @param subject 邮件主题 | |
| * @param to 收件人 | |
| * @param cc 抄送 | |
| * @param bcc 密抄 | |
| * @param body 邮件内容, | |
| * @Param mimeType 邮件内容的 MIME 类型,例如: 'text/plain', 'text/html;charset=utf-8' | |
| * @return | |
| */ | |
| public static void send(String addresser, String subject, String to, String cc, String bcc, String body, String mimeType) { | |
| // 初始化发件账号的参数 | |
| String email = "{Your Sender Email}" | |
| String password = "{Your Password}" | |
| String host = "{Your Host}" // 例如: "smtp.google.com" | |
| String port = "{Your port}" // 例如: "465" "587" | |
| // 初始化 Properties 参数 | |
| Properties props = System.getProperties() | |
| props.put("mail.smtp.user", email) | |
| props.put("mail.smtp.host", host) | |
| props.put("mail.smtp.port", port) | |
| props.put("mail.smtp.starttls.enable","true") | |
| props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory") | |
| props.put("mail.smtp.ssl.trust", host) // 将 host 改为 "*" 则信任所有 host. | |
| // 初始化 Message 参数 | |
| MimeMessage message = new MimeMessage(Session.getDefaultInstance(props)) | |
| message.setFrom(new InternetAddress(addresser)) | |
| message.addRecipients(Message.RecipientType.TO, new InternetAddress(to)) | |
| message.addRecipients(Message.RecipientType.CC, new InternetAddress(cc)) | |
| message.addRecipients(Message.RecipientType.CC, new InternetAddress(bcc)) | |
| message.setSubject(subject) | |
| message.setContent(body, mimeType) | |
| try { | |
| // 发送邮件 | |
| Transport.send(message, email, password) | |
| } catch (MessagingException e) { | |
| e.printStackTrace() | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment