import java.io.File; import java.net.URL; import org.apache.commons.mail.Email; 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 SendMail { /** * 利用 Apache Commons Email 组件(commons-email-1.4)发送邮件 * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { // simpleMail(); sendHTMLMail(); // sendAttachmentMail(); } public void simpleMail(){ Email email = new SimpleEmail(); email.setHostName("smtp.test.com"); email.setSmtpPort(25); email.setAuthentication("service@test.com","admin123"); email.setSSLOnConnect(true); try { email.setFrom("admin@test.com"); email.setSubject("TestMail"); email.setMsg("This is a test mail ... :-)"); email.addTo("admin@test.com"); email.send(); } catch (EmailException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static void sendHTMLMail() throws Exception{ // Create the email message HtmlEmail email = new HtmlEmail(); email.setHostName("smtp.test.com"); email.setSmtpPort(25); email.setAuthentication("admin@test.com", "password");//用户名,密码 email.setSSLOnConnect(true); email.addTo("admin@test.com", "Ken"); email.addTo("admin2@test.com");// 设置收件人 email.setFrom("admin@test.com", "Me"); email.setSubject("Test HTML email "); // embed the image and get the content id URL url = new URL("http://qq.test.com/images/111.png"); String cid = email.embed(url, "qhcaifu logo"); // set the html message email.setHtmlMsg("<html>The qhcaifu logo - <img src=\"cid:"+cid+"\"></html>"); // set the alternative message email.setTextMsg("Your email client does not support HTML messages"); // send the email email.send(); } private static void sendAttachmentMail() { MultiPartEmail email = new MultiPartEmail();// 如果要发送带附件的邮件,需使用这个类 email.setHostName("smtp.test.com"); email.setAuthentication("service@test.com","admin123"); email.setCharset("UTF-8"); try { email.setFrom("admin@test.com");// 设置发件人 email.addTo("admin@test.com");// 设置收件人 email.setSubject("测试邮件");// 设置主题 email.setMsg("测试邮件测试邮件测试邮件");// 设置邮件内容 File file = new File("C:\\testEmail.txt");// 要发送的附件 EmailAttachment attachment = new EmailAttachment(); attachment.setPath(file.getPath()); attachment.setName(file.getName()); attachment.setDescription("附件描述"); attachment.setDisposition(EmailAttachment.ATTACHMENT);// 附件的类型 email.attach(attachment); email.send(); System.out.println("发送成功"); } catch (EmailException e) { e.printStackTrace(); } } }
-------所需jar包:
-------异常解决: