现在来研究一下发送带附件的邮件是怎么发送的,当然这篇中的附件主要为服务器上的附件,下一篇将会介绍通过URL来获取附件并发送邮件。
主要代码如下:import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.MultiPartEmail;
public class AttachmentLocalTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// Create the p_w_upload
EmailAttachment p_w_upload = new EmailAttachment();
//附件地址
p_w_upload.setPath("E:/test.txt");
p_w_upload.setDisposition(EmailAttachment.ATTACHMENT);
//附件说明
p_w_upload.setDescription("Picture of John");
//附件名称
//这里需要加上文件的后缀名
p_w_upload.setName("test2.txt");
// Create the email message
MultiPartEmail email = new MultiPartEmail();
//邮件服务器
email.setHostName("smtp.126.com");
//端口号
email.setSmtpPort(25);
//用户名、密码
email.setAuthenticator(new DefaultAuthenticator("yuke198907@126.com", "密码你懂的"));
email.setSSLOnConnect(true);
try {
//收件人
email.addTo("yuke@iisant.com", "yuke");
//发件人
email.setFrom("yuke198907@126.com", "yuke198907");
//标题
email.setSubject("The picture");
//内容
email.setMsg("Here is the picture you wanted");
// add the p_w_upload
email.attach(p_w_upload);
// send the email
email.send();
} catch (EmailException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}