import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.commons.mail.MultiPartEmail;
import org.apache.commons.mail.SimpleEmail;
public class EmailHelper {
public static final String FORMUSER="****@itm-cn.cn";
public static final String FORMPASS="****";
public static final String FORMEMAIL_HOSTNAME="smtp.ym.163.com";
public static void main(String[] args) {
sendAttachment();
}
//发送普通邮件
public static void sendText()
{
SimpleEmail email = new SimpleEmail();
email.setTLS(true);
email.setHostName(FORMEMAIL_HOSTNAME);
email.setAuthentication(FORMUSER,FORMPASS); //用户名和密码
try
{
email.addTo(FORMUSER); //接收方
email.setFrom(FORMUSER); //发送方
email.setSubject("Java Mail Test"); //标题
email.setMsg("Just a simple send test ."); //内容
email.send();
} catch (EmailException e) {
e.printStackTrace();
}
}
//发送普通邮件
public static void sendHtml()
{
HtmlEmail email = new HtmlEmail();
email.setTLS(true);
email.setHostName(FORMEMAIL_HOSTNAME);
email.setAuthentication(FORMUSER,FORMPASS); //用户名和密码
try
{
email.addTo(FORMUSER); //接收方
email.setFrom(FORMUSER); //发送方
email.setSubject("Java Mail Test"); //标题
email.setHtmlMsg("Just a simple send test .<a href=\"http://baidu.com\">baidu</a>"); //内容
email.send();
} catch (EmailException e) {
e.printStackTrace();
}
}
//发送带附件的邮件
public static void sendAttachment(){
//创建一个Email附件
EmailAttachment emailAttachment = new EmailAttachment();
emailAttachment.setPath("E:/2.png");
//emailAttachment.setURL(new URL("http://www.blogjava.net/bulktree/picture/bulktree.jpg"));
emailAttachment.setDisposition(EmailAttachment.ATTACHMENT);
emailAttachment.setDescription("This is Smile picture");
//emailAttachment.setName("bulktree");//若不设置该方法将使用原文件名称
// 创建一个email
MultiPartEmail multipartemail = new MultiPartEmail();
multipartemail.setTLS(true);
multipartemail.setHostName(FORMEMAIL_HOSTNAME);
multipartemail.setAuthentication(FORMUSER, FORMPASS);
try {
multipartemail.addTo(FORMUSER, "username");
multipartemail.setFrom(FORMUSER, "工作室");
multipartemail.setSubject("This is a attachment Email");
multipartemail.setMsg("this a attachment Eamil Test");
multipartemail.attach(emailAttachment); //添加附件
multipartemail.send(); //发送邮件
} catch (EmailException e) {
e.printStackTrace();
}
}
}
附带文件:使用到的jar