1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
| public class MailUtil extends Thread { private final String from = "1074544350@qq.com"; private final String checkCode = "wnozaopvasqigchb"; private final String email;
public QQMail(String username, String password, String email) { this.email = email; }
@Override public void run() { try { Properties prop = new Properties(); String host = "smtp.qq.com"; prop.setProperty("mail.host", host); prop.setProperty("mail.transport.protocol", "smtp"); prop.setProperty("mail.smtp.auth", "true");
MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); prop.put("mail.smtp.ssl.enable", "true"); prop.put("mail.smtp.ssl.socketFactory", sf);
Session session = Session.getDefaultInstance(prop, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(from, checkCode); } }); session.setDebug(true); Transport ts = session.getTransport(); ts.connect(host, from, checkCode); MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.setFrom(new InternetAddress(from)); mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(email)); mimeMessage.setSubject("Test");
MimeBodyPart image = new MimeBodyPart(); DataHandler dataHandler = new DataHandler(new FileDataSource("/Users/cian/Code/Study/Java/JavaWeb/src/main/resources/1.jpg")); image.setDataHandler(dataHandler); image.setContentID("1.jpg"); MimeBodyPart text = new MimeBodyPart(); text.setContent("这是一封邮件正文带图片<img width=\"400px\" src='cid:1.jpg'>的邮件", "text/html;charset=UTF-8"); MimeMultipart mm = new MimeMultipart(); mm.addBodyPart(text); mm.addBodyPart(image); mm.setSubType("related"); mimeMessage.setContent(mm); mimeMessage.saveChanges(); ts.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); ts.close(); } catch (Exception e) { throw new RuntimeException(e); } }
public static void main(String[] args) { MailUtil mail = new MailUtil("test", "123456", "1074544350@qq.com"); mail.start(); } }
|