当前位置: 移动技术网 > IT编程>开发语言>Java > Java发送带html标签内容的邮件实例代码

Java发送带html标签内容的邮件实例代码

2019年07月22日  | 移动技术网IT编程  | 我要评论

如下所示:

package test;

import javax.mail.internet.internetaddress;
import javax.mail.internet.mimemessage;
import javax.mail.internet.mimeutility;
import javax.mail.session;
import javax.mail.messagingexception;
import javax.mail.transport;

public class sendhtmlmail {
  public static void sendmessage(string smtphost, string from, string to,string subject, string messagetext) throws messagingexception,
      java.io.unsupportedencodingexception {

    // step 1: configure the mail session
    system.out.println("configuring mail session for: " + smtphost);
    java.util.properties props = new java.util.properties();
    props.setproperty("mail.smtp.auth", "true");// 指定是否需要smtp验证
    props.setproperty("mail.smtp.host", smtphost);// 指定smtp服务器
    props.put("mail.transport.protocol", "smtp");
    session mailsession = session.getdefaultinstance(props);
    mailsession.setdebug(false);// 是否在控制台显示debug信息

    // step 2: construct the message
    system.out.println("constructing message - from=" + from + " to=" + to);
    internetaddress fromaddress = new internetaddress(from);
    internetaddress toaddress = new internetaddress(to);

    mimemessage testmessage = new mimemessage(mailsession);
    testmessage.setfrom(fromaddress);
    testmessage.addrecipient(javax.mail.message.recipienttype.to, toaddress);
    testmessage.setsentdate(new java.util.date());
    testmessage.setsubject(mimeutility.encodetext(subject, "gb2312", "b"));

    testmessage.setcontent(messagetext, "text/html;charset=gb2312");
    system.out.println("message constructed");

    // step 3: now send the message
    transport transport = mailsession.gettransport("smtp");
    transport.connect(smtphost, "riteng_mes", "ri-teng1234");
    transport.sendmessage(testmessage, testmessage.getallrecipients());
    transport.close();

    system.out.println("message sent!");
  }

  public static void main(string[] args) {

    string smtphost = "10.131.119.36";
    string from = "riteng_mes@casetekcorp.com";
    string to = "qiang1_zhang@intra.casetekcorp.com";
    string subject = "html邮件测试"; // subject javamail自动转码

    stringbuffer themessage = new stringbuffer();
    themessage.append("<h2><font color=red>这倒霉孩子</font></h2>");
    themessage.append("<hr>");
    themessage.append("<i>年年失望年年望</i>");
    themessage.append("<table border='1'><tr><td>aaa</td><td>bbb</td></tr><tr><td>ccc</td><td>ddd</td></tr></table>");

    try {
      sendhtmlmail.sendmessage(smtphost, from, to, subject,themessage.tostring());
    } catch (javax.mail.messagingexception exc) {
      exc.printstacktrace();
    } catch (java.io.unsupportedencodingexception exc) {
      exc.printstacktrace();
    }
  }
}

以上就是小编为大家带来的java发送带html标签内容的邮件实例代码全部内容了,希望大家多多支持移动技术网~

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网