发送邮件时Arraylist为消息

时间:2014-05-22 12:25:29

标签: java sendmail

我有这个arraylist;

ArrayList<String> list = new ArrayList<String>();

我已从一些数据库查询填充此arraylist,我必须将此列表作为电子邮件发送。

public void sendMail(ArrayList carriers) throws Exception {  
        Email email = new SimpleEmail();
        email.setHostName("mail.test.com.tr");
        email.setSmtpPort(587);
        email.setAuthentication("testuser@mail.test.com.tr","testuserpass");
        email.setSSLOnConnect(false);
        email.setFrom("testuser@mail.test.com.tr");
        email.setSubject("Test Information List");
        email.setMsg("Last 1 hour Information;\n"+carriers);
        email.addTo("test@mail.test.com.tr");
        email.send();
        System.out.println("email sended succesfully.");
        } 

当我调用此sendMail(列表)时;方法邮件成功地来到我的邮箱。但是此列表中的所有字符串通常都在消息正文中并排显示。我想让所有的琴弦垂直对齐。让我解释一下;

Now;
trying1, trying2, trying3

Desired format;
trying1
trying2
trying3

我该如何处理?

- 解决 -

StringBuilder b = new StringBuilder();
for(Object carrier : carriers)
b.append(carrier).append("\n");  

String carriersString = b.toString();

上面的行添加到sendMail()方法,代码的开头。以下行编辑到;

email.setMsg("Last 1 hour Information;\n"+carriersString);

感谢@Icewind

1 个答案:

答案 0 :(得分:3)

您必须手动将字符串连接到所需的格式。默认的toString()方法会将值连接到comma

这样的事情:

StringBuilder b = new StringBuilder();
for(String carrier : carriers)
    b.append(carrier).append("\n");

String carriersString = b.toString();

或apache commons中的StringUtils(http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html):

String carriersString = StringUtils.join(carriers, "\n");

...略...

email.setMsg("Last 1 hour Information;\n"+carriersString);