Stirng []无法转换为字符串

时间:2018-07-03 01:46:58

标签: java arrays string

我无法解决我的错误。我想要一个向多人发送电子邮件的程序。到目前为止,这是我的代码...

public static void sendEmailWithAttachments(String host, String port,
            final String userName, final String password, String[] toAddress,
            String subject, String message, String[] attachFiles)
            throws AddressException, MessagingException {
        // sets SMTP server properties
        Properties properties = new Properties();
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.port", port);
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.user", userName);
        properties.put("mail.password", password);

        // creates a new session with an authenticator
        Authenticator auth = new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userName, password);
            }
        };
        Session session = Session.getInstance(properties, auth);

        // creates a new e-mail message
        Message msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(userName));
        InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
        msg.setRecipients(Message.RecipientType.TO, toAddresses);
        msg.setSubject(subject);
        msg.setSentDate(new Date());

toAddress中的{new Internet Address(toAddress)}是表示无法将String []转换为String的部分。

InternetAddress[] toAddresses = { new InternetAddress(toAddress) };

提前感谢您的帮助:)

4 个答案:

答案 0 :(得分:1)

只需遍历toAddress,将每个字符串包装到InternetAddress中,然后将其放入toAddresses

InternetAddress[] toAddresses = new InternetAddress[toAddress.length];

for(int i = 0; i < toAddresses; i++) {
   toAddresses[i] = new InternetAddress(toAddress[i]);
}

答案 1 :(得分:0)

尝试首先创建Internet地址数组,然后分配一个值:

InternetAddress[] toAddresses = new InternetAddress[1];
toAddresses[0] = new InternetAddress(toAddress);
msg.setRecipients(Message.RecipientType.TO, toAddresses);

答案 2 :(得分:0)

InternetAddress的构造函数将String作为参数而不是String数组。因此,您应该在下面进行尝试:

  InternetAddress[] toAddresses = { new InternetAddress(toAddress[0]) };

答案 3 :(得分:0)

错误消息几乎说明了一切。您尝试将toAddress(一个String的数组)传递给InternetAddress的构造函数,并且InternetAddress的唯一一个参数构造函数接受String,不是String[]

您知道您需要将String的数组转换为InternetAddress的数组,并且显然您希望new InternetAddress可以以某种方式做到这一点。但是,可悲的是,事情并非如此。您必须一次循环转换一次String,例如:

InternetAddress[] toAddresses = new InternetAddress[toAddress.length];
for (int i = 0; i < toAddress.length; ++i)
{
    toAddresses[i] = new InternetAddress(toAddress[i]);
}