使用java代码发送qq邮件
程序员文章站
2022-05-18 20:58:10
...
首先导入需要的jar包
新建一个test类
package cn.z;
public class Test {
public static void main(String[] args) {
Mail mail = new Mail();
System.out.println("sending");
mail.send();
System.out.println("finished!");
}
}
新建一个mail类
package cn.z;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Mail {
private String mailServer, from, to, mailSubject, mailContent;
private String username, password;
public Mail() {
//设置邮件信息
username = "你的qq号码@qq.com";
password = "密码"; //后面会说到怎么使用,如果可以的话,就用qq密码
mailServer = "smtp.qq.com";
from = "由谁发送,一般是你的qq号码@qq.com";
to = "发送给谁@qq.com";
mailSubject = "问好";
mailContent = "好久不见,最近好吗?";
}
public void send(){
//设置邮件服务器
Properties prop = System.getProperties();
prop.put("mail.smtp.host", mailServer);
prop.put("mail.smtp.port", "25");
prop.put("mail.smtp.starttls.enable", "true");
prop.put("mail.smtp.auth", "true");
//产生Session服务
EmailAuthenticator mailauth = new EmailAuthenticator(username, password);
Session mailSession = Session.getInstance(prop, (Authenticator)mailauth);
try {
//封装Message对象
Message message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(from)); //设置发件人
message.setRecipient(Message.RecipientType.TO,
new InternetAddress(to));//设置收件人
message.setSubject(mailSubject);//设置主题
message.setContent(mailContent, "text/html;charset=utf8");//设置内容(设置字符集处理乱码问题)
message.setSentDate(new Date());//设置日期
//创建Transport实例,发送邮件
Transport tran = mailSession.getTransport("smtp");
tran.send(message, message.getAllRecipients());
tran.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
新建一个EmailAuthenticator类
package cn.z;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
/**
* EmailAuthenticator
* 继承自Authenticator
*/
public class EmailAuthenticator extends Authenticator{
private String username = null;
private String userpass = null;
void setUsername(String username) {
this.username = username;
}
void setUserpass(String userpass) {
this.userpass = userpass;
}
public EmailAuthenticator(String username, String userpass) {
super();
setUsername(username);
setUserpass(userpass);
}
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, userpass);
}
}
记得打开你的邮箱POP3/SMTP服务
点击设置
设置里面的账户
开启这个
然后发送短信设置开启,开启后他会给你一个密码,用那个密码填到上面的emil类中的密码就可以了