Java使用网易邮箱服务器发送邮件实例
1 下载发送mail需要的jar包
activation.jar 与 mail.jar
2 创建 SendMail 类
3 代码如下
import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import cn.founder.common.globals.Constants;
public class SendMail {
public int send(String tfrom, String tto, String ttitle, String tcontent) {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.263.net");//自己到网上查找网易发邮件的smtp服务地址 你的发件邮箱如果是163 你就查找163的发件服务器
props.put("mail.smtp.auth", "true");
Session s = Session.getInstance(props, null);
s.setDebug(true);
Message message = new MimeMessage(s);
try {
Address from = new InternetAddress(tfrom);
message.setFrom(from);
Address to = new InternetAddress(tto);
message.setRecipient(Message.RecipientType.TO, to);
sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
message.setSubject("=?utf-8?B?"+enc.encode(ttitle.getBytes("utf-8"))+"?=");
message.setContent(tcontent, "text/html;charset=utf-8");
message.setSentDate(new Date());
message.saveChanges();
Transport transport = s.getTransport("smtp");
//第一个参数是发件服务器 第二个是你发件的邮箱名 第三个是你发件邮箱的密码
transport.connect("smtp.263.net",”发件邮箱”,”发件邮箱密码”);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
return 0;
} catch (Exception e) {
e.printStackTrace();
return 1;
}
}
/**
* getEmailServiceIp
* @return EmailServiceIp
*/
public static void main(String[] args) {
//第一个参数 发件邮箱 第二个收件邮箱 第三个 邮件内容
new SendMail().send("yunlong090614@163.com", "1063342004@qq.com", "更改密码校验", "尊敬的用户你好,您的校验码为:65432</br>xxxx");
}