【问题标题】:HTML Formatting in the Automated Mail Content自动邮件内容中的 HTML 格式
【发布时间】:2011-05-01 23:49:05
【问题描述】:
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);

String rowFormat = "%8s %8s %8s %8s%n";
pw.printf(rowFormat, "Col A", "Col B", "Col C", "Col XY");
pw.printf(rowFormat, "A", "19", "Car", "55");
pw.printf(rowFormat, "X", "21", "Train C", "-4");
pw.printf(rowFormat, "B", "-9", "Bike", "0");
String message = sw.toString();
System.out.println(message);

以上程序打印下表,对齐完美。

Col A    Col B    Col C   Col XY   
    A       19      Car       55   
    X       21  Train C       -4   
    B       -9     Bike        0  

我没有打印string message,而是将字符串传递给另一个函数,该函数发送电子邮件,邮件内容为string message

mail.setContent(message.toString(),"text/plain");

这就是我在邮件中将内容设置为消息的方式。

但是表格的对齐方式不合适,因为我在打印字符串时确实收到了。必须做什么才能收到与字符串打印格式相似的邮件内容。

我可以意识到将mime类型设置为text/html并使用<table>标签来形成表格将帮助我完成所需的任务。

请告诉我,必须插入<table><tr><th> 标签的方式和位置,以便在邮件内容中找到表格格式。

【问题讨论】:

    标签: java html string email mime-types


    【解决方案1】:

    就个人而言,我会使用 velocity 来处理类似的事情,但是,我认为这就是您想要的:

    String headerFormat = "<tr><th>%8s</th><th>%8s</th><th>%8s</th><th>%8s%n</th></tr>";
    String rowFormat = "<tr><td>%8s</td><td>%8s</td><td>%8s</td><td>%8s%n</td></tr>";
    
    pw.printf(headerFormat, "Col A", "Col B", "Col C", "Col XY");
    pw.printf(rowFormat, "A", "19", "Car", "55");
    pw.printf(rowFormat, "X", "21", "Train C", "-4");
    pw.printf(rowFormat, "B", "-9", "Bike", "0");
    
    String message = "<table>" + sw.toString() + "</table>";
    System.out.println(message);
    

    您可以在 html 表格here 上获取更多信息。

    【讨论】:

    • 您可能可以去掉 '%8' 和 '%n' 值,而只使用 '%s' - 但这并不重要,因为大多数(如果不是全部)html 渲染器会无论如何忽略多余的空格。
    猜你喜欢
    • 2012-10-20
    • 1970-01-01
    • 2012-01-28
    • 1970-01-01
    • 2021-05-06
    • 1970-01-01
    • 1970-01-01
    • 2015-02-22
    • 2016-12-23
    相关资源
    最近更新 更多