概述:之前用QQ邮箱做了发邮件,可是到接收邮件时却不行了,这个问题还没解决,后面就用163邮箱来做就可以
1.到163邮箱的设置去打开SMTP和imap服务,SMTP是发送邮件,IMAP是接收邮件
2.发送邮件:
public static String send(String toEmail , String _content,String subject) throws MessagingException {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.163.com");// 指定SMTP服务器
props.put("mail.smtp.auth", "true");// 指定是否需要SMTP验证
String from = "*****@163.com";
String to = toEmail;//接收的Email
String content = _content;//邮件内容
String host = "smtp.163.com";
String user = "*****@163.com";
String password = "*****";
Session mailSession = Session.getDefaultInstance(props);
Message message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(from));// 发件人
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));// 收件人
message.setSubject(subject);// 邮件主题
message.setContent(content,"text/html;charset=utf-8");// 邮件内容
message.saveChanges();
Transport transport = mailSession.getTransport("smtp");
transport.connect(host, user, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
return from;
}
3.接收邮件
public class ReceiveEmail {
private MimeMessage msg = null;
private String saveAttchPath = "";
private StringBuffer bodytext = new StringBuffer();
private String dateformate = "yy-MM-dd HH:mm:ss";
public ReceiveEmail(MimeMessage msg){
this.msg = msg;
}
public void setMsg(MimeMessage msg) {
this.msg = msg;
}
/**
* 获取发送邮件者信息
* @return
* @throws MessagingException
*/
public String getFrom() throws MessagingException{
InternetAddress[] address = (InternetAddress[]) msg.getFrom();
String from = address[0].getAddress();//发件人的邮箱地址
if(from == null){
from = "";
}
String personal = address[0].getPersonal();//类似昵称
if(personal == null){
personal = "";
}
String fromaddr = personal +"";
return fromaddr;
}
/**
* 获取邮件收件人,抄送,密送的地址和信息。根据所传递的参数不同 "to"-->收件人,"cc"-->抄送人地址,"bcc"-->密送地址
* @param type
* @return
* @throws MessagingException
* @throws UnsupportedEncodingException
*/
public String getMailAddress(String type) throws MessagingException, UnsupportedEncodingException{
String mailaddr = "";
String addrType = type.toUpperCase();
InternetAddress[] address = null;
if(addrType.equals("TO")||addrType.equals("CC")||addrType.equals("BCC")){
if(addrType.equals("TO")){
address = (InternetAddress[]) msg.getRecipients(Messa