1、java 发送邮件 用javax.mail 包
1、写邮件发送类 sendMail
public class SendMail {
private MimeMessage mimeMsg; // MIME邮件对象
private Session session; // 邮件会话对象
private String smtphome="mail.bsteel.com"; // 邮件服务器
private Properties props; // 系统属性
private String username; // smtp认证用户名和密码
private String password ; // smtp认证密码
private Multipart mp; // Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成MimeMessage对象
/**
*
*/
public SendMail(){
}
public SendMail(String smtphome,String username,String password) {
this.smtphome = smtphome;
this.username = username;
this.password = password;
setSmtpHost(this.smtphome);
createMimeMessage();
}
/**
* @param hostName
* String
*/
public void setSmtpHost(String hostName) {
System.out.println("设置系统属性:mail.smtp.host = " + hostName);
if (props == null)
props = System.getProperties(); // 获得系统属性对象
props.put("mail.smtp.host", hostName); // 设置SMTP主机
}
/**
* @return boolean
*/
public boolean createMimeMessage() {
try {
System.out.println("准备获取邮件会话对象!");
session = Session.getDefaultInstance(props, null); // 获得邮件会话对象
} catch (Exception e) {
System.err.println("获取邮件会话对象时发生错误!" + e);
return false;
}
System.out.println("准备创建MIME邮件对象!");
try {
mimeMsg = new MimeMessage(session); // 创建MIME邮件对象
mp = new MimeMultipart();
return true;
} catch (Exception e) {
System.err.println("创建MIME邮件对象失败!" + e);
return false;
}
}
.....
详情请见附件
1、把email 包copy 到项目中:
2、设置邮件发送的服务器
3、设置smtp认证用户名和密码
4、设置内容,发送邮箱,接收邮箱,主题
5、调用sendout() 发送方法