需要的jar包 commons-email-1.2.jar commons-logging-1.1.jar mail.jar
view plaincopy to clipboardprint?
package com.beckham.common.email;
import javax.mail.internet.MimeUtility;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.MultiPartEmail;
import org.apache.commons.mail.SimpleEmail;
public class CommonMail {
public static void main(String[] args) throws Exception {
CommonMail mail = new CommonMail();
mail.sendMutiMail();
}
// 发送简单邮件
public void sendSimpleMail() throws Exception {
SimpleEmail email = new SimpleEmail();
email.setHostName("smtp.gmail.com"); // 发送服务器
email.setAuthentication("gaowm0207@gmail.com", "password"); // 发送邮件的用户名和密码
email.addTo("459978392@qq.com", "a"); // 接收邮箱
email.setFrom("gaowm0207@163.com", "a"); // 发送邮箱
email.setSubject("测试主题");// 主题
email.setMsg("这里是邮件内容"); // 内容
email.setSmtpPort(465); // 端口
email.setSSL(true); // gmail需要设置SSL安全设置
email.setCharset("GBK"); // 编码
email.send();
}
// 发送带附件的邮件
public void sendMutiMail() throws Exception{
EmailAttachment attachment = new EmailAttachment();
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription("python resource");
attachment.setPath("src/com/beckham/common/email/附件.txt") ;
attachment.setName(MimeUtility.encodeText("附件.txt")) ; //设置附件的中文编码
MultiPartEmail email = new MultiPartEmail();
email.setHostName("smtp.163.com"); // 发送服务器
email.setAuthentication("gaowm0207@163.com", "password"); // 发送邮件的用户名和密码
email.addTo("459978392@qq.com", "a"); // 接收邮箱
email.setFrom("gaowm0207@163.com", "a"); // 发送邮箱
email.setSubject("测试主题");// 主题
email.setMsg("这里是邮件内容"); // 内容
email.setCharset("GBK"); // 编码
// 添加附件
email.attach(attachment);
// 发送邮件
email.send();
}
}
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/gaowenming/archive/2010/02/02/5281050.aspx