import java.util.Properties;
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 SendMailBean {
private MimeMessage mimeMsg; // MIME邮件消息对象(实际发送的电子邮件的信息)
private Session session; // 邮件会话对象
private Properties props; // 系统属性
private String username = "xiaohai"; // smtp认证用户名
private String password = "295361921"; // smtp认证密码
private Multipart mp;// 用于保存电子邮件内容的容器
public SendMailBean(String smtp) {
setSmtpHost(smtp);
createMimeMessage();
}
/**
* 设置邮件服务器的主机名
*
*/
public void setSmtpHost(String hostName) {
if (props == null) {
props = System.getProperties();
}
props.put("mail.cn.ufinity.com", hostName);
props.put("cn.ufinity.com", "true");
}
public void createMimeMessage() {
try {
session = Session.getDefaultInstance(props, null);
} catch (Exception e) {
System.err.println("创建邮件会话对象失败!" + e);
return;
}
try {
mimeMsg = new MimeMessage(session); // 创建MIME邮件消息对象
mp = new MimeMultipart();// 创建保存电子邮件内容的容器
} catch (Exception e) {
System.err.println("创建MIME邮件消息对象失败!" + e);
}
}
/**
* 设置发送Email所需的基本信息 subject——邮件主题,from——发件人地址,to——收件人地址,content——邮件内容
*/
public boolean setMail(String subject, String from, String to,
String content) {
try {
mimeMsg.setSubject(subject, "GBK");
mimeMsg.setFrom(new InternetAddress(from));
BodyPart bp = new MimeBodyPart();
bp.setText(content);
mp.addBodyPart(bp);
mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress
.parse(to));
mimeMsg.setContent(mp);
mimeMsg.saveChanges();
return true;
} catch (Exception e) {
System.err.println("邮件设置失败!" + e);
return false;
}
}
/**
* 发送Email
*/
public boolean sendout() {
try {
Transport transport = session.getTransport("smtp");// 获得Transport对象来完成邮件的发送
transport.connect((String) props.get("mail.cn.ufinity.com"),
username, password);
transport.sendMessage(mimeMsg, mimeMsg
.getRecipients(Message.RecipientType.TO));
transport.close();
} catch (Exception e) {
System.err.println("邮件发送失败!" + e);
return false;
}
System.out.println("邮件发送成功!");
return true;
}
public static void main(String args[]) {
SendMailBean mail = new SendMailBean("156.102.12.205");
mail.setMail("测试发送Email", "",
"", "测试通过javaMail发送邮件");
mail.sendout();
}
}
//当然还需要发送邮件的jar包