java mail 发送qq以及网易邮件
1.准备工作:如果是用java mail发送qq邮件 和163邮件 需要注意的地方;
(1)qq、163邮箱必须生成授权码才可以发送邮件,
这里使用的QQ邮箱 我们可以在邮箱帮助中找到QQ邮箱的pop3跟smtp服务器地址已经开放的相应端口 一般是465,或者是587
(2)网易的163邮箱也必须生成授权码,这个是自己设置的;
这两个包是必须导入的
下面贴出方法实现:
方法1:
package test;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class QWmaster {
private static boolean send_qqmail(String strMail, String strTitle, String strText){
boolean bret = false;
try
{
final Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.qq.com");
//你自己的邮箱
props.put("mail.user", "xxx你的qq邮箱[email protected]");
//你开启pop3/smtp时的验证码
props.put("mail.password", "你的pop3/smtp验证码");
props.put("mail.smtp.port", "25");
props.put("mail.smtp.starttls.enable", "true");
Authenticator authenticator = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
String userName = props.getProperty("mail.user");
String password = props.getProperty("mail.password");
return new PasswordAuthentication(userName, password);
}
};
// 使用环境属性和授权信息,创建邮件会话
Session mailSession = Session.getInstance(props, authenticator);
// 创建邮件消息
MimeMessage message = new MimeMessage(mailSession);
// 设置发件人
String username = props.getProperty("mail.user");
InternetAddress form = new InternetAddress(username);
message.setFrom(form);
InternetAddress to = new InternetAddress(strMail);
message.setRecipient(RecipientType.TO, to);
// 设置邮件标题
message.setSubject(strTitle);
// 设置邮件的内容体
message.setContent(strText, "text/html;charset=UTF-8");
// 发送邮件
Transport.send(message);
bret = true;
}
catch (AddressException e) {
e.printStackTrace();
}
catch (MessagingException e) {
e.printStackTrace();
}
catch (Exception e){
e.printStackTrace();
}
return bret;
}
private static boolean send_163mail(String strMail, String strTitle, String strText){
boolean bret = false;
try
{
final Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.163.com");
// 发件人的账号
props.put("mail.user", "[email protected]");
//发件人的密码
props.put("mail.password", "你的网易163邮箱验证码");
// 构建授权信息,用于进行SMTP进行身份验证
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// 用户名、密码
String userName = props.getProperty("mail.user");
String password = props.getProperty("mail.password");
return new PasswordAuthentication(userName, password);
}
};
// 使用环境属性和授权信息,创建邮件会话
Session mailSession = Session.getInstance(props, authenticator);
// 创建邮件消息
MimeMessage message = new MimeMessage(mailSession);
// 设置发件人
String username = props.getProperty("mail.user");
InternetAddress form = new InternetAddress(username);
message.setFrom(form);
// 设置收件人
InternetAddress to = new InternetAddress(strMail);
message.setRecipient(RecipientType.TO, to);
// 设置邮件标题
message.setSubject(strTitle);
// 设置邮件的内容体
message.setContent(strText, "text/html;charset=UTF-8");
// 发送邮件
Transport.send(message);
bret = true;
}
catch (AddressException e) {
e.printStackTrace();
}
catch (MessagingException e) {
e.printStackTrace();
}
catch (Exception e){
e.printStackTrace();
}
return bret;
}
public static void main(String[] args) {
if (send_qqmail("xxx对方的的qq邮箱[email protected]", "[华宇科技公司]邮箱发送", "<body><p>希望通过你</p></body>"))
System.out.println("QQ邮件发送成功");
if (send_163mail("xxx对方的的163邮箱[email protected]", "测试网易邮箱发送", "<body><p>你们好吗</p></body>"))
System.out.println("网易邮件发送成功");
}
}
方法2:
package test;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import com.sun.mail.util.MailSSLSocketFactory;
/**
* 发送邮件的测试程序(适用qq邮箱)
* 通过本人的qq邮箱: [email protected] 发送邮件
* @author miaoch
*
*/
public class Testqq {
//发送的邮箱 内部代码只适用qq邮箱
private static final String USER = "[email protected]";
//授权密码 通过QQ邮箱设置->账户->POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务->开启POP3/SMTP服务获取
private static final String PWD = "xxxxx";
private String[] to;
private String[] cc;//抄送
private String[] bcc;//密送
private String[] fileList;//附件
private String subject;//主题
private String content;//内容,可以用html语言写
public void sendMessage() throws MessagingException, UnsupportedEncodingException, GeneralSecurityException {
// 配置发送邮件的环境属性
final Properties props = new Properties();
//下面两段代码是设置ssl和端口,不设置发送不出去。
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.socketFactory", sf);
// props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
//props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465"); // 465
// 表示SMTP发送邮件,需要进行身份验证
props.setProperty("mail.transport.protocol", "smtp");// 设置传输协议
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.qq.com");//QQ邮箱的服务器 如果是企业邮箱或者其他邮箱得更换该服务器地址
// 发件人的账号
props.put("mail.user", USER);
// 访问SMTP服务时需要提供的密码
props.put("mail.password", PWD);
// 构建授权信息,用于进行SMTP进行身份验证
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// 用户名、密码
String userName = props.getProperty("mail.user");
String password = props.getProperty("mail.password");
return new PasswordAuthentication(userName, password);
}
};
// 使用环境属性和授权信息,创建邮件会话
Session mailSession = Session.getInstance(props, authenticator);
// 创建邮件消息
MimeMessage message = new MimeMessage(mailSession);
BodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
// 设置发件人
InternetAddress form = new InternetAddress(
props.getProperty("mail.user"));
message.setFrom(form);
//发送
if (to != null) {
String toList = getMailList(to);
InternetAddress[] iaToList = new InternetAddress().parse(toList);
message.setRecipients(RecipientType.TO, iaToList); // 收件人
}
//抄送
if (cc != null) {
String toListcc = getMailList(cc);
InternetAddress[] iaToListcc = new InternetAddress().parse(toListcc);
message.setRecipients(RecipientType.CC, iaToListcc); // 抄送人
}
//密送
if (bcc != null) {
String toListbcc = getMailList(bcc);
InternetAddress[] iaToListbcc = new InternetAddress().parse(toListbcc);
message.setRecipients(RecipientType.BCC, iaToListbcc); // 密送人
}
message.setSentDate(new Date()); // 发送日期 该日期可以随意写,你可以写上昨天的日期(效果很特别,亲测,有兴趣可以试试),或者抽象出来形成一个参数。
message.setSubject(subject); // 主题
message.setText(content); // 内容
//显示以html格式的文本内容
messageBodyPart.setContent(content,"text/html;charset=utf-8");
multipart.addBodyPart(messageBodyPart);
//保存多个附件
if(fileList!=null){
addTach(fileList, multipart);
}
message.setContent(multipart);
// 发送邮件
Transport.send(message);
}
public void setTo(String[] to) {
this.to = to;
}
public void setCc(String[] cc) {
this.cc = cc;
}
public void setBcc(String[] bcc) {
this.bcc = bcc;
}
public void setSubject(String subject) {
this.subject = subject;
}
public void setContent(String content) {
this.content = content;
}
public void setFileList(String[] fileList) {
this.fileList = fileList;
}
private String getMailList(String[] mailArray) {
StringBuffer toList = new StringBuffer();
int length = mailArray.length;
if (mailArray != null && length < 2) {
toList.append(mailArray[0]);
} else {
for (int i = 0; i < length; i++) {
toList.append(mailArray[i]);
if (i != (length - 1)) {
toList.append(",");
}
}
}
return toList.toString();
}
//添加多个附件
public void addTach(String fileList[], Multipart multipart) throws MessagingException, UnsupportedEncodingException {
for (int index = 0; index < fileList.length; index++) {
MimeBodyPart mailArchieve = new MimeBodyPart();
FileDataSource fds = new FileDataSource(fileList[index]);
mailArchieve.setDataHandler(new DataHandler(fds));
mailArchieve.setFileName(MimeUtility.encodeText(fds.getName(),"UTF-8","B"));
multipart.addBodyPart(mailArchieve);
}
}
//以下是演示demo
public static void main(String args[]) {
Testqq mail = new Testqq();
mail.setSubject("这个是标题"); //uppbhonpzlsrbdfi
mail.setContent("这个是内容");
//收件人 可以发给其他邮箱(163等) 下同
mail.setTo(new String[] {"嘻嘻嘻@qq.com","[email protected]"});
//抄送
// mail.setCc(new String[] {"[email protected]","[email protected]"});
//密送
// mail.setBcc(new String[] {"[email protected]","[email protected]"});
//发送附件列表 可以写绝对路径 也可以写相对路径(起点是项目根目录) 如果你没有就注释掉或者写别的不然会包空指针
mail.setFileList(new String[] {"src/2301.jpg","src/01.jpg"});
//发送邮件
try {
mail.sendMessage();
System.out.println("发送邮件成功!");
} catch (Exception e) {
System.out.println("发送邮件失败!");
e.printStackTrace();
}
}
}
方法3:
package test;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Test {
// 发送邮件的账号
// public static String ownEmailAccount = "[email protected]";
public static String ownEmailAccount = "[email protected]";
// 发送邮件的密码------》授权码
// public static String ownEmailPassword = "xxx";
public static String ownEmailPassword = "xxx";
// 发送邮件的smtp 服务器 地址
// public static String myEmailSMTPHost = "smtp.163.com";
public static String myEmailSMTPHost = "smtp.qq.com";
// 发送邮件对方的邮箱
// public static String receiveMailAccount = "[email protected]";
public static String receiveMailAccount = "[email protected]";
public static void main(String[] args) throws Exception {
Properties prop = new Properties();
// 设置邮件传输采用的协议smtp
prop.setProperty("mail.transport.protocol", "smtp");
// 设置发送人邮件服务器的smtp地址
// 这里以网易的邮箱smtp服务器地址为例
prop.setProperty("mail.smtp.host", myEmailSMTPHost);
// 设置验证机制
prop.setProperty("mail.smtp.auth", "true");
// SMTP 服务器的端口 (非 SSL 连接的端口一般默认为 25, 可以不添加, 如果开启了 SSL 连接,
// 需要改为对应邮箱的 SMTP 服务器的端口, 具体可查看对应邮箱服务的帮助,
// QQ邮箱的SMTP(SLL)端口为465或587, 其他邮箱自行去查看)
/*QQ邮箱需要的163邮箱不需要*/
final String smtpPort = "465";
prop.setProperty("mail.smtp.port", smtpPort);
prop.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
prop.setProperty("mail.smtp.socketFactory.fallback", "false");
prop.setProperty("mail.smtp.socketFactory.port", smtpPort);
/*QQ邮箱需要的163邮箱不需要*/
// 创建对象回话跟服务器交互
Session session = Session.getInstance(prop);
// 会话采用debug模式
session.setDebug(true);
// 创建邮件对象
Message message = createSimpleMail(session);
Transport trans = session.getTransport();
// 链接邮件服务器
trans.connect(ownEmailAccount, ownEmailPassword);
// 发送信息
trans.sendMessage(message, message.getAllRecipients());
// 关闭链接
trans.close();
}
/**
* @Title: createSimpleMail
* @Description: 创建邮件对象
* @author: chengpeng
* @param @param session
* @param @return
* @param @throws Exception 设定文件
* @return Message 返回类型
* @throws
*/
public static Message createSimpleMail(Session session) throws Exception {
MimeMessage message = new MimeMessage(session);
// 设置发送邮件地址,param1 代表发送地址 param2 代表发送的名称(任意的) param3 代表名称编码方式
// message.setFrom(new InternetAddress("[email protected]", "张三", "utf-8"));
//网易给QQ发会标记为垃圾邮件
message.setFrom(new InternetAddress("[email protected]", "张三", "utf-8"));// 代表收件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress(receiveMailAccount, "李四", "utf-8"));
// To: 增加收件人(可选)
/*message.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress("[email protected]", "USER_DD", "UTF-8"));
// Cc: 抄送(可选)
message.setRecipient(MimeMessage.RecipientType.CC, new InternetAddress("[email protected]", "USER_EE", "UTF-8"));
// Bcc: 密送(可选)
message.setRecipient(MimeMessage.RecipientType.BCC, new InternetAddress("[email protected]", "USER_FF", "UTF-8"));*/
// 设置邮件主题
message.setSubject("测试转发邮件");
// 设置邮件内容
message.setContent("早安,世界 你最近好吗!", "text/html;charset=utf-8");
// 设置发送时间
message.setSentDate(new Date());
// 保存上面的编辑内容
message.saveChanges();
// 将上面创建的对象写入本地
OutputStream out = new FileOutputStream("MyEmail.eml");
message.writeTo(out);
out.flush();
out.close();
return message;
}
}