Java发送Email真的很简单

有个同事讲个笑话,资深程序员跟一个新来的科班实习生说,去写个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();
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值