十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
我给你提供一个我在项目里面实际使用的代码.
创新互联专注于青岛企业网站建设,响应式网站设计,成都做商城网站。青岛网站建设公司,为青岛等地区提供建站服务。全流程按需策划设计,专业设计,全程项目跟踪,创新互联专业和态度为您提供的服务
这是我基于一个网上的代码自己修改封装过来的.
你可以参考一下
/**
*
* @author Sglee
*
*/
public class SimpleMail {
private static String encode = null;
static {
if ("\\".equals(File.separator)) {
encode = "GBK";
} else {
encode = "UTF-8";
}
}
/**
* 以文本格式发送邮件
*
* @param mailInfo
* @return
*/
public static boolean sendTextMail(MailInfo mailInfo) {
for (int i = 0; i 3; i++) {
// 判断是否需要身份认证
MyAuthenticator authenticator = null;
Properties properties = mailInfo.getProperties();
if (mailInfo.isValidate()) {
// 如果需要身份认证,则创建一个密码验证器
authenticator = new MyAuthenticator(mailInfo.getUsername(),
mailInfo.getPassword());
}
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
Session sendMailSession = Session.getDefaultInstance(properties,
authenticator);
if (mailInfo.isDebug()) {
sendMailSession.setDebug(true);
}
try {
Message mailMessage = new MimeMessage(sendMailSession);// 根据session创建一个邮件消息
Address from = new InternetAddress(mailInfo.getFromAddress());// 创建邮件发送者地址
mailMessage.setFrom(from);// 设置邮件消息的发送者
// Address to = new InternetAddress(mailInfo.getToAddress());//
// 创建邮件的接收者地址
// mailMessage.setRecipient(Message.RecipientType.TO, to);//
// 设置邮件消息的接收者
mailMessage.setRecipients(Message.RecipientType.TO,
wrapAddress(mailInfo.getToAddress()));
// InternetAddress ms = new
// InternetAddress(mailInfo.getMsAddress());
// mailMessage.setRecipient(Message.RecipientType.BCC, ms); //
// 密送人
mailMessage.setRecipients(Message.RecipientType.BCC,
wrapAddress(mailInfo.getMsAddress()));
mailMessage.setSubject(mailInfo.getSubject());// 设置邮件消息的主题
mailMessage.setSentDate(new Date());// 设置邮件消息发送的时间
// mailMessage.setText(mailInfo.getContent());//设置邮件消息的主要内容
// MimeMultipart类是一个容器类,包含MimeBodyPart类型的对象
Multipart mainPart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();// 创建一个包含附件内容的MimeBodyPart
// 设置HTML内容
messageBodyPart.setContent(mailInfo.getContent(),
"text/html; charset=" + encode);
mainPart.addBodyPart(messageBodyPart);
// 存在附件
String[] filePaths = mailInfo.getAttachFileNames();
if (filePaths != null filePaths.length 0) {
for (String filePath : filePaths) {
messageBodyPart = new MimeBodyPart();
File file = new File(filePath);
if (file.exists()) {// 附件存在磁盘中
FileDataSource fds = new FileDataSource(file);// 得到数据源
messageBodyPart
.setDataHandler(new DataHandler(fds));// 得到附件本身并至入BodyPart
messageBodyPart.setFileName("=?" + encode + "?B?"
+ file.getName());// 得到文件名同样至入BodyPart
mainPart.addBodyPart(messageBodyPart);
}
}
}
// 将MimeMultipart对象设置为邮件内容
mailMessage.setContent(mainPart);
Transport.send(mailMessage);// 发送邮件
return true;
} catch (Exception e) {
e.printStackTrace();
try {
java.util.concurrent.TimeUnit.SECONDS.sleep(5);
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
return false;
}
/**
* 将string[]包装成EmailAddress
* @param mailInfo
* @return
* @throws AddressException
*/
private static Address [] wrapAddress(String[] adds) throws AddressException {
// String[] adds = mailInfo.getToAddress();
if(adds == null || adds.length == 0){
return null;
}
Address []to = new Address[adds.length];
for(int i = 0;iadds.length;i++){
to[i]=new InternetAddress(adds[i]);
}
return to;
}
/**
* 以HTML格式发送邮件
*
* @param mailInfo
* @return
*/
public static boolean sendHtmlMail(MailInfo mailInfo) {
for (int i = 0; i 3; i++) {
// 判断是否需要身份认证
MyAuthenticator authenticator = null;
Properties properties = mailInfo.getProperties();
if (mailInfo.isValidate()) {
// 如果需要身份认证,则创建一个密码验证器
authenticator = new MyAuthenticator(mailInfo.getUsername(),
mailInfo.getPassword());
}
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
Session sendMailSession = Session.getDefaultInstance(properties,
authenticator);
if (mailInfo.isDebug()) {
sendMailSession.setDebug(true);
}
try {
Message mailMessage = new MimeMessage(sendMailSession);// 根据session创建一个邮件消息
Address from = new InternetAddress(mailInfo.getFromAddress());// 创建邮件发送者地址
mailMessage.setFrom(from);// 设置邮件消息的发送者
// Address to = new InternetAddress(mailInfo.getToAddress());//
// 创建邮件的接收者地址
// mailMessage.setRecipient(Message.RecipientType.TO, to);//
// 设置邮件消息的接收者
mailMessage.setRecipients(Message.RecipientType.TO,
wrapAddress(mailInfo.getToAddress()));
// InternetAddress ms = new
// InternetAddress(mailInfo.getMsAddress());
// mailMessage.setRecipient(Message.RecipientType.BCC, ms); //
// 密送人
mailMessage.setRecipients(Message.RecipientType.BCC,
wrapAddress(mailInfo.getMsAddress()));
mailMessage.setSubject(mailInfo.getSubject());// 设置邮件消息的主题
mailMessage.setSentDate(new Date());// 设置邮件消息发送的时间
// MimeMultipart类是一个容器类,包含MimeBodyPart类型的对象
Multipart mainPart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();// 创建一个包含HTML内容的MimeBodyPart
// 设置HTML内容
messageBodyPart.setContent(mailInfo.getContent(),
"text/html; charset=" + encode);
mainPart.addBodyPart(messageBodyPart);
// 存在附件
String[] filePaths = mailInfo.getAttachFileNames();
if (filePaths != null filePaths.length 0) {
sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
for (String filePath : filePaths) {
messageBodyPart = new MimeBodyPart();
File file = new File(filePath);
if (file.exists()) {// 附件存在磁盘中
FileDataSource fds = new FileDataSource(file);// 得到数据源
messageBodyPart
.setDataHandler(new DataHandler(fds));// 得到附件本身并至入BodyPart
messageBodyPart.setFileName("=?" + encode + "?B?"
+ enc.encode(EmailFileNameConvert.changeFileName(file.getName()).getBytes())
+ "?=");// 得到文件名同样至入BodyPart
mainPart.addBodyPart(messageBodyPart);
}
}
}
// 将MimeMultipart对象设置为邮件内容
mailMessage.setContent(mainPart);
Transport.send(mailMessage);// 发送邮件
return true;
} catch (Exception e) {
e.printStackTrace();
try {
java.util.concurrent.TimeUnit.SECONDS.sleep(5);
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
return false;
}
}
/**
* 封装邮件的基本信息
*
* @author Sglee
*
*/
public class MailInfo implements Serializable{
/**
*
*/
private static final long serialVersionUID = -3937199642590071261L;
private String mailServerHost;// 服务器ip
private String mailServerPort;// 端口
private long timeout;// 超时时间
private String fromAddress;// 发送者的邮件地址
private String[] toAddress;// 邮件接收者地址
private String[] msAddress;// 密送地址
private String username;// 登录邮件发送服务器的用户名
private String password;// 登录邮件发送服务器的密码
private boolean validate = false;// 是否需要身份验证
private String subject;// 邮件主题
private String content;// 邮件内容
private String[] attachFileNames;// 附件的文件地址
private boolean debug;// 调试模式
public Properties getProperties() {
Properties p = new Properties();
p.put("mail.smtp.host", this.mailServerHost);
p.put("mail.smtp.port", this.mailServerPort);
p.put("mail.smtp.auth", validate ? "true" : "false");
p.put("mail.smtp.timeout", this.timeout);
return p;
}
public String getMailServerHost() {
return mailServerHost;
}
public void setMailServerHost(String mailServerHost) {
this.mailServerHost = mailServerHost;
}
public String getMailServerPort() {
return mailServerPort;
}
public void setMailServerPort(String mailServerPort) {
this.mailServerPort = mailServerPort;
}
public String getFromAddress() {
return fromAddress;
}
public void setFromAddress(String fromAddress) {
this.fromAddress = fromAddress;
}
public String[] getToAddress() {
return toAddress;
}
public void setToAddress(String[] toAddress) {
this.toAddress = toAddress;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isValidate() {
return validate;
}
public void setValidate(boolean validate) {
this.validate = validate;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String[] getAttachFileNames() {
return attachFileNames;
}
public void setAttachFileNames(String[] attachFileNames) {
this.attachFileNames = attachFileNames;
}
public void setMsAddress(String[] msAddress) {
this.msAddress = msAddress;
}
public String[] getMsAddress() {
return msAddress;
}
public void setDebug(boolean debug) {
this.debug = debug;
}
public boolean isDebug() {
return debug;
}
public void setTimeout(long timeout) {
this.timeout = timeout;
}
public long getTimeout() {
return timeout;
}
}
public class MyAuthenticator extends Authenticator {
private String username = null;
private String password = null;
public MyAuthenticator() {
};
public MyAuthenticator(String username, String password) {
this.username = username;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
}
注意一下:
Myeclipse自带的JavaEE5.jar和java mail会发生冲突
找到ME下的javeee包
D:\MyEclipse 8.5\Common\plugins\com.genuitec.eclipse.j2eedt.core_8.5.0.me201003231033\data\libraryset\EE_5\javaee.jar
用rar等解压工具解开javaee.jar,删除里面的javax\mail文件夹(可以先备份javaee.jar)
也即,以后都不能使用javaee.jar里面的邮件api发送邮件了.
import java.util.*;
import javax.mail.*;import javax.mail.internet.*;
public class JMail {
public void SendMail(String Topic,String Content){ Properties props=new Properties(); props.put("mail.smtp.host","smtp.163.com"); props.put("mail.smtp.auth","true"); Session s=Session.getInstance(props); s.setDebug(false); MimeMessage message=new MimeMessage(s); MimeMultipart mp=new MimeMultipart(); BodyPart body = new MimeBodyPart(); InternetAddress from; InternetAddress to; try{ from=new InternetAddress("发件人邮箱"); message.setFrom(from); to = new InternetAddress("收件人邮箱"); message.setRecipient(Message.RecipientType.TO,to); message.setSubject(Topic,"utf-8"); body.setContent(Content, "text/html;charset=utf-8"); mp.addBodyPart(body); message.setContent(mp); message.setSentDate(new Date()); message.saveChanges(); Transport transport=s.getTransport("smtp"); transport.connect("smtp.163.com(邮件服务商,这是163的)","发件邮箱","发件邮箱密码"); transport.sendMessage(message,message.getAllRecipients()); transport.close(); } catch(AddressException e){ e.printStackTrace(); } catch(MessagingException e){ e.printStackTrace(); } }}
public boolean mainto()
{
boolean flag = true;
//建立邮件会话
Properties pro = new Properties();
pro.put("mail.smtp.host","smtp.qq.com");//存储发送邮件的服务器
pro.put("mail.smtp.auth","true"); //通过服务器验证
Session s =Session.getInstance(pro); //根据属性新建一个邮件会话
//s.setDebug(true);
//由邮件会话新建一个消息对象
MimeMessage message = new MimeMessage(s);
//设置邮件
InternetAddress fromAddr = null;
InternetAddress toAddr = null;
try
{
fromAddr = new InternetAddress(451144426+"@qq.com"); //邮件发送地址
message.setFrom(fromAddr); //设置发送地址
toAddr = new InternetAddress("12345367@qq.com"); //邮件接收地址
message.setRecipient(Message.RecipientType.TO, toAddr); //设置接收地址
message.setSubject(title); //设置邮件标题
message.setText(content); //设置邮件正文
message.setSentDate(new Date()); //设置邮件日期
message.saveChanges(); //保存邮件更改信息
Transport transport = s.getTransport("smtp");
transport.connect("smtp.qq.com", "451144426", "密码"); //服务器地址,邮箱账号,邮箱密码
transport.sendMessage(message, message.getAllRecipients()); //发送邮件
transport.close();//关闭
}
catch (Exception e)
{
e.printStackTrace();
flag = false;//发送失败
}
return flag;
}
这是一个javaMail的邮件发送代码,需要一个mail.jar
代码如下:
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class EmailTest {
public static void main(String[] args) throws Exception{
Properties props = new Properties();
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", "smtp.163.com");
Session session = Session.getInstance(props,
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication("xxx","xxx");//这里分别填写发送email的用户名、密码
}
}
);
session.setDebug(true);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("xxx"));//这里是发送方的email地址如:xxx@163.com
msg.setSubject("test javamail");
msg.setRecipients(RecipientType.TO,
InternetAddress.parse("xxx"));//这里是接收方的email地址如:xxx@163.com
msg.setContent("a href=\"\"谷歌/a","text/html;charset=gb2312");
Transport.send(msg);
}
}