Java实现邮件代理发送

时间:2023-03-09 16:41:01
Java实现邮件代理发送
使用java实现邮件发送

首先需要添加jar文件
mailapi.jar
stmp.jar 1 import java.util.Properties; import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage; /**
* 邮件发送代理线程
* @author helingfeng
*
*/
public class EmailAgent implements Runnable{ private String username;
private String title;
private String content; public EmailAgent(){
//
}
public EmailAgent(String email,String title,String content){
this.username = email;
this.title = title;
this.content = content;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getTitle() {
return title;
} public void setTitle(String title) {
this.title = title;
} public String getContent() {
return content;
} public void setContent(String content) {
this.content = content;
}
public void run() {
Properties props = new Properties();
//配置协议
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.transport.protocol","smtp"); //创建会话
Session session = Session.getInstance(props);
session.setDebug(true); Message message = null;
Transport transport = null; try {
//创建信息对象
message = new MimeMessage(session);
message.setSubject(title);
message.setText(content);
//参数(用户名)
message.setFrom(new InternetAddress("857190327@qq.com"));
//创建传输对象
transport = session.getTransport();
//参数 (STMP服务器、端口、用户名、密码)
transport.connect("smtp.qq.com", 587, "857190327@qq.com", "密码");
transport.sendMessage(message, new Address[]{new InternetAddress(username)});
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}finally{
try{
if(transport.isConnected()){
transport.close();
transport = null;
}
}catch(MessagingException e1){
e1.printStackTrace();
}
}
}
}