Java发送邮件
一、导入相关邮箱jar包,及邮箱配置参照上一篇 传送点
二、实现代码
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.File;
import java.util.Properties;
public class SendMessage {
private static final String TO = "***@126.com";
private static final String FORM = "****@qq.com";
private static final String HOST = "smtp.qq.com";
private static final String AUTH_CODE = "*****";
public void Send() {
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", Msg.HOST);
properties.put("mail.smtp.auth", true);
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(Msg.FORM, Msg.AUTH_CODE);
}
});
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(Msg.FORM));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(Msg.TO));
message.setSubject("biubiubiu");
BodyPart bodyPart = new MimeBodyPart();
bodyPart.setText("我是正文开始");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(bodyPart);
bodyPart = new MimeBodyPart();
File file = new File("D:/test.txt");
if (!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
DataSource source = new FileDataSource(file);
bodyPart.setDataHandler(new DataHandler(source));
bodyPart.setFileName(file.getName());
multipart.addBodyPart(bodyPart);
message.setContent(multipart);
Transport.send(message);
System.out.println("哔哩哔哩 (゜-゜)つロ 干杯~-bilibili 发送成功!");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
三、成功演示
