1 package com.project.c3p0demo32.tools; 2 3 import javax.mail.Session; 4 import javax.mail.internet.InternetAddress; 5 import javax.mail.internet.MimeMessage; 6 import javax.mail.internet.MimeMessage.RecipientType; 7 import java.util.Properties; 8 import javax.mail.Message; 9 import javax.mail.MessagingException; 10 import javax.mail.Transport; 11 import javax.mail.internet.AddressException; 12 13 public class SendMail { 14 //发送的邮箱地址(该邮件由谁发送) 15 public final static String sender =""; 16 //钥匙,有了钥匙邮件系统才能知道你是有权限用该邮箱发送邮件的 17 public final static String key=""; 18 public static void main(String[] args){ 19 try { 20 new SendMail().send("", "邮件测试", "你已经成功购买了GirlCloset中的商品!"); 21 } catch (AddressException e) { 22 e.printStackTrace(); 23 } catch (MessagingException e) { 24 e.printStackTrace(); 25 } 26 27 } 28 /** 29 * 30 * @param receiver 邮件接收方 31 * @param title 邮件标题 32 * @param content 邮件正文 33 * @throws AddressException 34 * @throws MessagingException 35 */ 36 public void send(String receiver, String title, String content) throws AddressException,MessagingException { 37 Properties properties = new Properties(); 38 39 properties.put("mail.transport.protocol", "smtp");// 连接协议 40 41 properties.put("mail.smtp.host", "smtp.qq.com");// 主机名 42 43 properties.put("mail.smtp.port", 465);// 端口号 44 45 properties.put("mail.smtp.auth", "true"); 46 47 properties.put("mail.smtp.ssl.enable", "true");//设置是否使用ssl安全连接 ---一般都使用 48 49 properties.put("mail.debug", "true");//设置是否显示debug信息 true 会在控制台显示相关信息 50 51 //得到回话对象 52 53 Session session = Session.getInstance(properties); 54 55 // 获取邮件对象 56 57 Message message = new MimeMessage(session); 58 59 //设置发件人邮箱地址 60 61 message.setFrom(new InternetAddress(sender)); 62 63 //设置收件人地址 64 message.setRecipients(RecipientType.TO,new InternetAddress[] { new InternetAddress(receiver) }); 65 66 //设置邮件标题 67 68 message.setSubject(title); 69 70 //设置邮件内容 71 72 message.setText(content); 73 74 //得到邮差对象 75 76 Transport transport = session.getTransport(); 77 78 //连接自己的邮箱账户 79 80 transport.connect(sender, key);//密码为刚才得到的授权码 81 82 //发送邮件 83 transport.sendMessage(message, message.getAllRecipients()); 84 } 85 86 }
原文:https://www.cnblogs.com/thelovelybugfly/p/10826894.html