- ·上一篇文章:怎么理解Java按引用传递?
- ·下一篇文章:Java中static、final用法及区别
怎么使用javaMail发送邮件?
-->
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 | import java.util.Date; import java.util.Map; import java.util.Properties; import javax.mail.Address; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class Sender { //填写 邮箱的用户名 / 密码 这个可以配置在一个properties 文件中 private String username = "xxxxxxxx@163.com"; private String password = "xxxxxxx"; //这里可以放一个对象进来不用非用map public void send(Map map)throws Exception{ /* * 创建Properties对象 * 设置连接的邮件服务地址 * 开启身份验证 */ Properties props = new Properties(); //这个是邮箱服务 qq 的就是smtp.qq.com props.put("mail.smtp.host", "smtp.163.com"); //开启验证 props.put("mail.smtp.auth", "true"); /* * 从 ProPerties中创建一个会话对象 ,连接邮件服务器 * getDefaultInstance(1,2) * 1Properties * 2身份验证对象Authenticator */ Session session = Session.getDefaultInstance(props,new Authenticator(){ @Override protected PasswordAuthentication getPasswordAuthentication() { // TODO Auto-generated method stub //这个事验证用户名和密码 return new PasswordAuthentication(username, password); } }); /* * 定义邮件内容对象 Message 将session 放入 */ Message msg = new MimeMessage(session); //定义发送人 Address from = new InternetAddress((String)map.get("from")); msg.setFrom(from); //定义收件人 Address to = new InternetAddress((String)map.get("to")); msg.setRecipient(Message.RecipientType.TO,to); /*Address[] tos = new Address[3]; msg.setRecipients(Message.RecipientType.TO, tos);*/ //定义抄送人 这里如果是多个的话 需要一个Address 数组 Address cc = new InternetAddress((String)map.get("cc")); msg.setRecipient(Message.RecipientType.CC,cc); //设置主题 msg.setSubject((String)map.get("subject")); /* * 添加邮件内容 * setContent */ msg.setContent((String)map.get("content"),"text/plain;charset=utf-8"); //发送时间 msg.setSentDate(new Date()); //保存消息 msg.saveChanges(); //发送消息 Transport.send(msg); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import java.util.HashMap; import java.util.Map; import com.etoak.util.Sender; public class Test { public static void main(String[] args) throws Exception { Map map = new HashMap(); map.put("from","xxxxxxx@163.com"); map.put("to","xxxxxx@qq.com"); map.put("cc", "xxxxxxxxxx@qq.com"); map.put("content", "这是邮件内容"); map.put("subject","这是主题"); Sender sd = new Sender(); sd.send(map); } } |
怎么使用javaMail发送邮件?