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
| import javax.mail.*; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties;
public class MailUtil { public static void main(String[] args) { sendMail("邮件接收者@qq.com","发送的信息"); }
public static void sendMail(String to, String code) { String myEmailAddr = "邮件发送者@qq.com"; Properties props = new Properties(); props.setProperty("mail.smtp.host", "smtp.qq.com"); props.setProperty("mail.smtp.auth", "true"); Session session = Session.getInstance(props);
Message message = new MimeMessage(session); try { Address fromAddr = new InternetAddress(myEmailAddr); message.setFrom(fromAddr);
Address toAddr = new InternetAddress(to); message.setRecipient(MimeMessage.RecipientType.TO, toAddr);
message.setSubject("来自*****系统的验证码"); message.setContent("这里是邮件的正文信息\n\n您的验证码为:" + code, "text/html;charset=UTF-8");
Transport transport = session.getTransport("smtp"); transport.connect("smtp.qq.com", myEmailAddr, "jxzk*******"); transport.sendMessage(message, message.getAllRecipients());
} catch (AddressException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } } }
|