【JAVA】使用javax.mail发送qq邮件
导入包
下载链接https://repo1.maven.org/maven2/com/sun/mail/javax.mail/
代码
package sample;import javax.imageio.ImageIO;
import javax.mail.*;
import javax.mail.internet.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Date;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;public class ScreenshotMailer {private static final String SMTP_HOST = "smtp.qq.com";private static final String SMTP_PORT = "587";private static final String FROM_EMAIL = "234@qq.com"; // 需替换为发件邮箱private static final String PASSWORD = "444ffffff"; // 需替换为邮箱授权码private static final String TO_EMAIL = "234@qq.com";public static void main(String[] args) {Timer timer = new Timer();timer.scheduleAtFixedRate(new TimerTask() {@Overridepublic void run() {try {// 1. 截屏Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());BufferedImage screenCapture = new Robot().createScreenCapture(screenRect);// 2. 保存临时文件File tempFile = File.createTempFile("screenshot_", ".png");ImageIO.write(screenCapture, "png", tempFile);// 3. 发送邮件sendEmailWithAttachment(tempFile);// 4. 删除临时文件tempFile.delete();} catch (Exception e) {e.printStackTrace();}}}, 0, 60 * 1000); // 立即开始,每分钟执行}private static void sendEmailWithAttachment(File attachment) throws Exception {Properties props = new Properties();props.put("mail.smtp.auth", "true");props.put("mail.smtp.starttls.enable", "true");props.put("mail.smtp.host", SMTP_HOST);props.put("mail.smtp.port", SMTP_PORT);Session session = Session.getInstance(props, new Authenticator() {protected PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(FROM_EMAIL, PASSWORD);}});Message message = new MimeMessage(session);message.setFrom(new InternetAddress(FROM_EMAIL));message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(TO_EMAIL));message.setSubject("定时截图 - " + new Date());MimeBodyPart textPart = new MimeBodyPart();textPart.setText("系统自动发送的定时截图");MimeBodyPart attachmentPart = new MimeBodyPart();attachmentPart.attachFile(attachment);Multipart multipart = new MimeMultipart();multipart.addBodyPart(textPart);multipart.addBodyPart(attachmentPart);message.setContent(multipart);Transport.send(message);}
}