邮件文本
mp.addBodyPart(bp);
} catch (Exception e) {
System.err.println("设置邮件正文时发生错误!" + e);
return false;
}
return true;
}
/**
* 增加发送附件
*
* @param filename
* 邮件附件的地址,只能是本机地址而不能是网络地址,否则抛出异常
* @return
*/
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);
} catch (Exception e) {
System.err.println("增加邮件附件:" + filename + "发生错误!" + e);
return false;
}
return true;
}
/**
* 设置发件人地址
*
* @param from
* 发件人地址
* @return
*/
public boolean setFrom(String from) {
System.out.println("设置发信人!");
try {
mimeMsg.setFrom(new InternetAddress(from));
} catch (Exception e) {
return false;
}
return true;
}
/**
* 设置收件人地址
*
* @param to
* 收件人的地址
* @return
*/
public boolean setTo(String to) {
System.out.println("设置收信人");
if (to == null)
return false;
try {
mimeMsg.setRecipients(javax.mail.Message.RecipientType.TO,
InternetAddress.parse(to));
} catch (Exception e) {
return false;
}
return true;
}
/**
* 发送附件
*
* @param copyto
* @return
*/
public boolean setCopyTo(String copyto) {
System.out.println("发送附件到");
if (copyto == null)
return false;
try {
mimeMsg.setRecipients(javax.mail.Message.RecipientType.CC,
InternetAddress.parse(copyto));
} catch (Exception e) {
return false;
}
return true;
}
/**
* 发送邮件
*
* @return
*/
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("smtp.hanyastar.com"),
username, password);
// 发送邮件
transport.sendMessage(mimeMsg, mimeMsg
.getRecipients(javax.mail.Message.RecipientType.TO));
System.out.println("发送邮件成功!");
transport.close();
} catch (Exception e) {
System.err.println("邮件发送失败!" + e.getMessage());
e.printStackTrace();
return false;
}
return true;
}
}
三、测试
package org.mail;
public class EmailUtils {
// subject 主题
// bodyContent 内容
// to 收件人
public static boolean sendMailForJavaByBoLun(String subject , String bodyContent , String to){
try{
Email themail = new Email("smtp.hanyastar.com");
themail.setNeedAuth(true);
themail.setSubject(subject);
themail.setBody(bodyContent);
themail.setTo(to);
// 填写邮件发件人信息描述。
themail.setFrom(new String("service"));
// 填写发件人邮箱与密码
themail.setNamePass("发件人邮箱", "发件人密码");
if(themail.sendout())
return true;
else
return false;
}catch(Exception e){
e.printStackTrace();
return false;
}
}
}
四、结果
设置系统属性:smtp.hanyastar.com = smtp.hanyastar.com
准备获取邮件会话对象!
准备创建MIME邮件对象!
设置smtp身份认证:mail.smtp.auth = true
设置邮件主题!
设置邮件体格式
设置收信人
设置发信人!
程序得到用户名与密码
正在发送邮件....
发送邮件成功!
五、常见错误
A)若你未使用我前面提到的架包,它将报javax.mail.NoSuchProviderException异