有个同事讲个笑话,资深程序员跟一个新来的科班实习生说,去写个B-Tree的算法。过来一下子,新来的实习生拿了张纸,上面写满了代码,跟资深程序员说:“写好了,这个直接敲入计算机就可以运行了”。于是乎,之后我们讨论什么问题,都直接说,“我这个代码是可以跑的,牛不牛?”
所以呢,别的也就不说了直接上源代码,这个简单的源代码编译运行就可以顺利执行,发送一段html的邮件。本程序是基于apache commons email ,而这个library的编译需要javamail的支持,你可以在这里下载到http://www.oracle.com/technetwork/java/javamail/index.html, 如果你没有的话。
当然你需要稍微修改一下里面的参数,毕竟我不能把我的邮箱以及密码贴进去。既然html都能发送,简单的文本就更不在话下了。当然如果你要增加附件参考 http://commons.apache.org/email/userguide.html
import org.apache.commons.mail.*;
import java.net.URL;
public class Main {
public static void main(String[] args) throws Exception
{
// Create the email message
HtmlEmail email = new HtmlEmail();
email.setHostName("smtp.gmail.com");
email.setSmtpPort(587);
email.setAuthenticator(new DefaultAuthenticator("your gmail account", "your gmail password"));
email.setTLS(true);
email.addTo("to email", "any name you like");
email.addCc("cc email", "any name you like");
email.setFrom("from email", "any name you like");
email.setSubject("Test email with inline image");
// embed the image and get the content id
URL url = new URL("http://www.apache.org/images/asf_logo_wide.gif");
String cid = email.embed(url, "Apache logo");
// set the html message
email.setHtmlMsg("<html>The apache logo - <img src=\"cid:"+cid+"\"><hr/></html>");
// set the alternative message
email.setTextMsg("Your email client does not support HTML messages");
// send the email
email.send();
}
}