java使用QQ邮箱发送邮件简单版。
下边直接开始,有用的话记得点个赞!
1. 添加需要的依赖
<!-- JavaMail -->
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.5</version>
</dependency>
<!-- JavaMail -->
2. QQ邮箱配置
登录到qq邮箱,进入到设置,账户管理。找到以下配置
3. 主要代码
import java.io.IOException;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import com.personal.front.base.util.Email_Util;
public class EmailSendUtil {
public static void main(String args[]) {
try {
// send_email("","");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void send_email(String email, String msg) throws IOException, AddressException, MessagingException {
String to = email; //发送到哪个邮箱
String subject = "有新留言!"; //邮件标题
String content = msg; //邮件内容
Properties properties = new Properties();
properties.put("mail.smtp.host", "smtp.qq.com");
properties.put("mail.smtp.port", "25");
properties.put("mail.smtp.auth", "true");
Authenticator authenticator = new Email_Util("xxxxx@qq.com(填你配置的qq邮箱)", "xx(对应授权码)");//
javax.mail.Session sendMailSession = javax.mail.Session.getDefaultInstance(properties, authenticator);
MimeMessage mailMessage = new MimeMessage(sendMailSession);
mailMessage.setFrom(new InternetAddress("xxxx@qq.com"));//发送邮件的地址/就填你的qq邮箱
// Message.RecipientType.TO属性表示接收者的类型为TO
mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
mailMessage.setSubject(subject, "UTF-8");
mailMessage.setSentDate(new Date());
// MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
Multipart mainPart = new MimeMultipart();
// 创建一个包含HTML内容的MimeBodyPart
BodyPart html = new MimeBodyPart();
html.setContent(content.trim(), "text/html; charset=utf-8");
mainPart.addBodyPart(html);
mailMessage.setContent(mainPart);
Transport.send(mailMessage);
}
}
4. 引用到的工具类
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
public class Email_Util extends Authenticator {
String userName = null;
String password = null;
public Email_Util() {
}
public Email_Util(String username, String password) {
this.userName = username;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(userName, password);
}
}
结束。