最近在开发工作遇到了这个,所以在这里就简单的整理一下,因为我这边只需要发送简单文本邮件,所以只是整理发送文本邮件的方法,图文或者其他的邮件,小伙伴们如果感兴趣,可以自己研究,也可以留言互相探讨。不多说了直接上代码,注意看注释,代码如下:
/**
* 使用SMTP协议发送电子邮件
*/
public class JavaEMail {
// 邮件发送协议
private final static String PROTOCOL = "smtp";
// SMTP邮件服务器
private final static String HOST = "smtp.sina.com";
// SMTP邮件服务器默认端口
private final static String PORT = "25";
// 是否要求身份认证
private final static String IS_AUTH = "true";
// 是否启用调试模式(启用调试模式可打印客户端与服务器交互过程时一问一答的响应消息)
private final static String IS_ENABLED_DEBUG_MOD = "true";
// 发件人
private static String from = "xxxxxxxxx@sina.com";//我这里的发件的邮箱是新浪邮箱
// 收件人
private static String to = ""; //定义收件邮箱地址
// 初始化连接邮件服务器的会话信息
private static Properties props = null;
//握手操作 ,准备工作
static {
props = new Properties();
props.setProperty("mail.transport.protocol", PROTOCOL);
props.setProperty("mail.smtp.host", HOST);
props.setProperty("mail.smtp.port", PORT);
props.setProperty("mail.smtp.auth", IS_AUTH);
props.setProperty("mail.debug",IS_ENABLED_DEBUG_MOD);
}
/**
* 发送简单的文本邮件
*/
public static void sendTextEmail(String email,String password) throws Exception {
// 创建Session实例对象
Session session = Session.getDefaultInstance(props,new MyAuthenticator());
// 创建MimeMessage实例对象
MimeMessage message = new MimeMessage(session);
// 设置发件人
message.setFrom(new InternetAddress(from));
// 设置邮件主题
message.setSubject("新密码邮件");
// 设置收件人
to=email;
message.setRecipient(RecipientType.TO, new InternetAddress(to));
// 设置发送时间
message.setSentDate(new Date());
// 设置纯文本内容为邮件正文
String emailText="您的新密码是:password,请牢记或者尽快修改密码! 某某";
message.setText(emailText);
// 保存并生成最终的邮件内容
message.saveChanges();
System.out.println("邮件格式内容:"+message);
// 获得Transport实例对象
Transport transport = session.getTransport();
// 打开连接
transport.connect("qingkekeji2011", "cyg6746666");
// 将message对象传递给transport对象,将邮件发送出去
transport.sendMessage(message, message.getAllRecipients());
// 关闭连接
transport.close();
}
/**
* 将邮件内容生成eml文件
* @param message 邮件内容
*/
public static File buildEmlFile(Message message) throws MessagingException, FileNotFoundException, IOException {
File file = new File("c:\\" + MimeUtility.decodeText(message.getSubject())+".eml");
message.writeTo(new FileOutputStream(file));
return file;
}
/**
* 向邮件服务器提交认证信息
*/
static class MyAuthenticator extends Authenticator {
private String username = "";//发件箱的用户名
private String password = "xxxxxx"; //密码
public MyAuthenticator() {
super();
}
public MyAuthenticator(String username, String password) {
super();
this.username = username;
this.password = password;
}
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
}
}
到这里基本功能介绍结束,在这里注意的是你设置的发送邮件的邮箱必须开启 smtp服务,具体可以上网查询,登录邮箱设置,具体不再赘述,同时运用的jar文件是
mail-1.4.7.jar,这个小伙伴们可以上网自行下载,如果找不到,可以给我留言。