刚好我也在学习,网上找了些:
专注于为中小企业提供网站建设、成都网站设计服务,电脑端+手机端+微信端的三站合一,更高效的管理,为中小企业疏勒免费做网站提供优质的服务。我们立足成都,凝聚了一批互联网行业人才,有力地推动了上千余家企业的稳健成长,帮助中小企业通过网站建设实现规模扩充和转变。
邮件群发:
收件人的地址设置为tomail i的形式,利用For循环向这些地址发送邮件,以实现群发的目的。
利用Address类设置邮件信息的收件人和发件人信息,在创建了邮件地址类后,通过message的setFrom()方法设置邮件的发件人,代码如下:
message.setFrom(from_mail);
设置收件人地址时使用setRecipient()方法设置收信人地址,代码如下:
message.setRecipient(type,address);
参数type为收件人类型。可以使用以下3个常量来区分收件人的类型:
1)Message.RecipientType.TO--发送。
2)Message.RecipientType.CC--抄送。
3)Message.RecipientType.BCC--暗 谢谢,请采纳!
使用JavaMail发送邮件需要用到mail.jar和activtion.jar两个包。
该类实现了较完整的邮件发送功能,包括以HTML格式发送,添加附件和抄送人。下面是具体的代码:
package cn.cgw.util.mail;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
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;
public class Mail {
private MimeMessage mimeMsg; //MIME邮件对象
private Session session; //邮件会话对象
private Properties props; //系统属性
private boolean needAuth = false; //smtp是否需要认证
//smtp认证用户名和密码
private String username;
private String password;
private Multipart mp; //Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成MimeMessage对象
/**
* Constructor
* @param smtp 邮件发送服务器
*/
public Mail(String smtp){
setSmtpHost(smtp);
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主机
}
/**
* 创建MIME邮件对象
* @return
*/
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;
}
}
/**
* 设置SMTP是否需要验证
* @param need
*/
public void setNeedAuth(boolean need) {
System.out.println("设置smtp身份认证:mail.smtp.auth = "+need);
if(props == null) props = System.getProperties();
if(need){
props.put("mail.smtp.auth","true");
}else{
props.put("mail.smtp.auth","false");
}
}
/**
* 设置用户名和密码
* @param name
* @param pass
*/
public void setNamePass(String name,String pass) {
username = name;
password = pass;
}
/**
* 设置邮件主题
* @param mailSubject
* @return
*/
public boolean setSubject(String mailSubject) {
System.out.println("设置邮件主题!");
try{
mimeMsg.setSubject(mailSubject);
return true;
}
catch(Exception e) {
System.err.println("设置邮件主题发生错误!");
return false;
}
}
/**
* 设置邮件正文
* @param mailBody String
*/
public boolean setBody(String mailBody) {
try{
BodyPart bp = new MimeBodyPart();
bp.setContent(""+mailBody,"text/html;charset=GBK");
mp.addBodyPart(bp);
return true;
} catch(Exception e){
System.err.println("设置邮件正文时发生错误!"+e);
return false;
}
}
/**
* 添加附件
* @param filename String
*/
public boolean addFileAffix(String filename) {
System.out.println("增加邮件附件:"+filename);
try{
BodyPart bp = new MimeBodyPart();
FileDataSource fileds = new FileDataSource(filename);
bp.setDataHandler(new DataHandler(fileds));
bp.setFileName(fileds.getName());
mp.addBodyPart(bp);
return true;
} catch(Exception e){
System.err.println("增加邮件附件:"+filename+"发生错误!"+e);
return false;
}
}
/**
* 设置发信人
* @param from String
*/
public boolean setFrom(String from) {
System.out.println("设置发信人!");
try{
mimeMsg.setFrom(new InternetAddress(from)); //设置发信人
return true;
} catch(Exception e) {
return false;
}
}
/**
* 设置收信人
* @param to String
*/
public boolean setTo(String to){
if(to == null)return false;
try{
mimeMsg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));
return true;
} catch(Exception e) {
return false;
}
}
/**
* 设置抄送人
* @param copyto String
*/
public boolean setCopyTo(String copyto)
{
if(copyto == null)return false;
try{
mimeMsg.setRecipients(Message.RecipientType.CC,(Address[])InternetAddress.parse(copyto));
return true;
}
catch(Exception e)
{ return false; }
}
/**
* 发送邮件
*/
public boolean sendOut()
{
try{
mimeMsg.setContent(mp);
mimeMsg.saveChanges();
System.out.println("正在发送邮件....");
Session mailSession = Session.getInstance(props,null);
Transport transport = mailSession.getTransport("smtp");
transport.connect((String)props.get("mail.smtp.host"),username,password);
transport.sendMessage(mimeMsg,mimeMsg.getRecipients(Message.RecipientType.TO));
transport.sendMessage(mimeMsg,mimeMsg.getRecipients(Message.RecipientType.CC));
//transport.send(mimeMsg);
System.out.println("发送邮件成功!");
transport.close();
return true;
} catch(Exception e) {
System.err.println("邮件发送失败!"+e);
return false;
}
}
/**
* 调用sendOut方法完成邮件发送
* @param smtp
* @param from
* @param to
* @param subject
* @param content
* @param username
* @param password
* @return boolean
*/
public static boolean send(String smtp,String from,String to,String subject,String content,String username,String password) {
Mail theMail = new Mail(smtp);
theMail.setNeedAuth(true); //需要验证
if(!theMail.setSubject(subject)) return false;
if(!theMail.setBody(content)) return false;
if(!theMail.setTo(to)) return false;
if(!theMail.setFrom(from)) return false;
theMail.setNamePass(username,password);
if(!theMail.sendOut()) return false;
return true;
}
/**
* 调用sendOut方法完成邮件发送,带抄送
* @param smtp
* @param from
* @param to
* @param copyto
* @param subject
* @param content
* @param username
* @param password
* @return boolean
*/
public static boolean sendAndCc(String smtp,String from,String to,String copyto,String subject,String content,String username,String password) {
Mail theMail = new Mail(smtp);
theMail.setNeedAuth(true); //需要验证
if(!theMail.setSubject(subject)) return false;
if(!theMail.setBody(content)) return false;
if(!theMail.setTo(to)) return false;
if(!theMail.setCopyTo(copyto)) return false;
if(!theMail.setFrom(from)) return false;
theMail.setNamePass(username,password);
if(!theMail.sendOut()) return false;
return true;
}
/**
* 调用sendOut方法完成邮件发送,带附件
* @param smtp
* @param from
* @param to
* @param subject
* @param content
* @param username
* @param password
* @param filename 附件路径
* @return
*/
public static boolean send(String smtp,String from,String to,String subject,String content,String username,String password,String filename) {
Mail theMail = new Mail(smtp);
theMail.setNeedAuth(true); //需要验证
if(!theMail.setSubject(subject)) return false;
if(!theMail.setBody(content)) return false;
if(!theMail.addFileAffix(filename)) return false;
if(!theMail.setTo(to)) return false;
if(!theMail.setFrom(from)) return false;
theMail.setNamePass(username,password);
if(!theMail.sendOut()) return false;
return true;
}
/**
* 调用sendOut方法完成邮件发送,带附件和抄送
* @param smtp
* @param from
* @param to
* @param copyto
* @param subject
* @param content
* @param username
* @param password
* @param filename
* @return
*/
public static boolean sendAndCc(String smtp,String from,String to,String copyto,String subject,String content,String username,String password,String filename) {
Mail theMail = new Mail(smtp);
theMail.setNeedAuth(true); //需要验证
if(!theMail.setSubject(subject)) return false;
if(!theMail.setBody(content)) return false;
if(!theMail.addFileAffix(filename)) return false;
if(!theMail.setTo(to)) return false;
if(!theMail.setCopyTo(copyto)) return false;
if(!theMail.setFrom(from)) return false;
theMail.setNamePass(username,password);
if(!theMail.sendOut()) return false;
return true;
}
}
你都没有设置邮件服务器....这句错误就是你没有设置邮件服务器或者你的用户名密码不正确
下面是我原来写的代码请参考:
首先是邮件模板的读取工具类
[java] view plaincopy
package gamutsoft.mail.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
public class ReadHTML {
/**
* @param args
*/
//public static void main(String[] args) {
// TODO Auto-generated method stub
public static String reMailString(){
//String info="";
StringBuffer buff=new StringBuffer();
InputStreamReader in=null;
BufferedReader br=null;
String path = System.getProperty("user.dir") + "/src/html/email2.html";
File file=new File(path);
try {
in=new InputStreamReader(new FileInputStream(file));
br=new BufferedReader(in);
String line=null;
while((line=br.readLine()) != null){
//System.out.println(line);
buff.append(line).append("\n");
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(in!=null){
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(br!=null){
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return buff.toString();
}
}
邮件的html模板:
email2.html(乱写的不喜勿喷)
[html] view plaincopy
html
head
meta http-equiv="content-type" content="text/html; charset=UTF-8"
/head
body
h4您好: /h4
a href=""网易/a
br
欢迎光临,呵呵呵呵呵呵呵呵额
br
十分感谢
h4您好:/h4
a href=""网易/a
br
欢迎光临,呵呵呵呵呵呵呵呵额
br
十分感谢
h4您好:/h4
a href=""网易/a
br
欢迎光临,呵呵呵呵呵呵呵呵额
br
十分感谢
h4您好:/h4
a href=""网易/a
br
欢迎光临,呵呵呵呵呵呵呵呵额
br
十分感谢
h4您好:/h4
a href=""网易/a
br
/html
邮件发送类:这里的邮箱是为了自己的隐私我乱写了下,如果测试的话还得填写正确的
[java] view plaincopy
package gamutsoft.mail.test;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
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;
public class MailTest1 {
public static void send() throws MessagingException, UnsupportedEncodingException {
String info=ReadHTML.reMailString();
//邮件服务器
String host="smtp.163.com";
//发件人
String from="1111@163.com";
//收件人
String to="1111@qq.com";
//抄送人
String toCC1="111111@163.com";
String toCC2="444444@126.com";
String username="5555555555@163.com";
String password="51234";
//邮件会话属性
//Properties p=System.getProperties();
Properties p=new Properties();
p.put("mail.smtp.host", host);
/*
p.put("mail.smtp.auth", "true");
//创建一个密码验证器
Authenticator auth = new MyAuthenticator(username, password);
//获得Session
Session session=Session.getDefaultInstance(p,auth);
*/
//////////////////sesion获得Transprot方法
Session session=Session.getDefaultInstance(p,null);
session.setDebug(true);
/////////////////////
//创建Message信息
MimeMessage message=new MimeMessage(session);
//创建邮件发送者地址
Address fromAD = new InternetAddress(from,"李建勋");
//nternetAddress(from)
//设置邮件发送者
message.setFrom(fromAD);
//创建邮件的接收地址
Address toAD = new InternetAddress(to);
//创建抄送人数组
Address toCAD1=new InternetAddress(toCC1);
Address toCAD2=new InternetAddress(toCC2);
Address [] toCs={toCAD1,toCAD2};
//设置邮件的接收地址
message.setRecipient(Message.RecipientType.TO,toAD);
message.addRecipients(Message.RecipientType.CC,toCs );
//设置发送时间
message.setSentDate(new Date());
//设置主题
message.setSubject("Hello JavaMail44");
/*
//设置消息正文,文本
message.setText("Welcome To JavaMail");
//设置HTML内容
message.setContent("a href=''百度/a","text/html;charset=utf-8");
*/
// MimeMultipart类是一个容器类,包含MimeBodyPart类型的对象
Multipart mainPart = new MimeMultipart();
//创建一个包含HTML内容的MimeBodyPart
BodyPart body=new MimeBodyPart();
//设置html内容
body.setContent(info,"text/html;charset=utf-8");
//将MimeMultipart设置为邮件内容
mainPart.addBodyPart(body);
message.setContent(mainPart);
///////////////////////sesion获得Transprot
Transport transport=session.getTransport("smtp");
transport.connect(host, username, password);
transport.sendMessage(message,message.getAllRecipients());
transport.close();
//////////////////////
// Transport.send(message);
}
public static void main(String[] args) throws MessagingException, UnsupportedEncodingException {
// TODO Auto-generated method stub
send();
}
}
接下来是MyAuthenticator类[java] view plaincopy
package gamutsoft.mail.test;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
public class MyAuthenticator extends Authenticator{
/*在使用Authenticator这个抽象类时,我们必须采用继承该抽象类的方式,并且该继承类必须具
* 有返回PasswordAuthentication对象(用于存储认证时要用到的用户名、密码)getPasswordAuthentication()
* 方法。并且要在Session中进行注册,使Session能够了解在认证时该使用哪个类。
* */
String username=null;
String password=null;
public MyAuthenticator(){
}
public MyAuthenticator(String username,String password){
this.username=username;
this.password=password;
}
public PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(username, password);
}
}