您的位置:首页 > 编程语言 > Java开发

JAVA发送邮件工具类

2013-10-15 18:16 316 查看
import java.util.Date;
import java.util.Properties;

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;

/**
* <p>Title:MailUtils.java</p>
* <p>Description:发送邮件工具类 </p>
*/
public class MailUtils {
private String server; //邮箱服务器
private String username; //邮箱名
private String password; //密码
public MailUtils(String server,String username,String password){
this.server=server;
this.username=username;
this.password=password;
}
public void send(String to_mail,String from_mail,String to_title,String to_content){
try{

//----接收邮件相关内容----
String to_contents = codeToString(to_content);
System.out.println("======="+to_content);
String to_titles = codeToString(to_title);
System.out.println("======="+to_title);
Properties props=new Properties();

//------建立邮件会话------

props.put("mail.smtp.host",server);//smtp.163.com
props.put("mail.smtp.auth","true");
Session s=Session.getInstance(props);
s.setDebug(true);
MimeMessage message=new MimeMessage(s);
//--给消息对象设置发件人、收件人、主题、发信时间--
InternetAddress from=new InternetAddress(from_mail);

message.setFrom(from);//发件人
InternetAddress to=new InternetAddress(to_mail);
message.setRecipient(Message.RecipientType.TO,to);

message.setSubject(to_title);

message.setSentDate(new Date());

BodyPart mdp=new MimeBodyPart();

//给BodyPart对象设置内容和格式的编码方式
mdp.setContent(to_content,"text/html;charset=utf-8");

//新建一个MimeMultipart对象用来存放BodyPart对象(事实上可以存放多个)
Multipart mm=new MimeMultipart();

//将BodyPart加入到MimeMultipart对象中(可以加入多个BodyPart)
mm.addBodyPart(mdp);

//把mm作为消息对象的内容
message.setContent(mm);

message.saveChanges();

Transport transport=s.getTransport("smtp");

//以smtp方式登录邮箱,第一个参数是发送邮件用的邮件服务器SMTP地址;第二个参数为用户名;第三个参数为密码
transport.connect(server,username,password);
transport.sendMessage(message,message.getAllRecipients());

transport.close();
}catch(MessagingException e){
e.printStackTrace();
System.out.println("发送邮件失败!");

}

}

//处理中文字符串的函数
public String codeToString(String str){
String s=str;
try{
byte tempB[]=s.getBytes("ISO-8859-1");
s=new String(tempB);
return s;
}catch(Exception e){
return s;
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: