邮件发送

来源:互联网 发布:js脚本小游戏 编辑:程序博客网 时间:2024/05/22 07:54
package com.company.email;import java.util.Properties;import javax.mail.Authenticator;import javax.mail.Message.RecipientType;import javax.mail.PasswordAuthentication;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;public class Email {private static final String TYPE = "text/html;charset=UTF-8";private static final String MAIL_SMTP_AUTH = "true";private static final String MAIL_SMTP_HOST = "smtp.163.com";private String username;private String password;public Email(String username, String password) {this.username = username;this.password = password;}public static void main(String[] args) throws Exception {Email email = new Email("zhangsan@163.com", "123456");email.sendTo("lisi@sina.com", "wangwu@qq.com", "hello", "How are you?");}public void sendTo(String receiver, String ccReceiver, String subject,String content) throws Exception {MimeMessage message = createMimeMessage(username, password);message.setFrom(new InternetAddress(username));message.setRecipient(RecipientType.TO, new InternetAddress(receiver));message.setRecipient(RecipientType.CC, new InternetAddress(ccReceiver));message.setSubject(subject);message.setContent(content, TYPE);Transport.send(message);}public static MimeMessage createMimeMessage(String username, String password) {Properties properties = createProperties(username, password);Authenticator authenticator = createAuthenticator(username, password);return new MimeMessage(Session.getInstance(properties, authenticator));}public static Properties createProperties(String username, String password) {Properties properties = new Properties();properties.put("mail.smtp.auth", MAIL_SMTP_AUTH);properties.put("mail.smtp.host", MAIL_SMTP_HOST);return properties;}public static Authenticator createAuthenticator(final String username,final String password) {return new Authenticator() {@Overrideprotected PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(username, password);}};}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}}
pom.xml 中依赖: 
<dependency><groupId>javax.mail</groupId><artifactId>mail</artifactId><version>1.4.7</version></dependency>

0 0
原创粉丝点击