以下是通过java邮件api发送邮件的java程序,现在的问题是我想在mailTo字段中输入多个地址。在下面的代码中,您可以看到mailTo的单个条目是avdq@abc.com。但是,我想通过avdq @ abc.com,tvdq @ abc.com和pvdq@abc.com传递多个条目。请告知如何实现这一目标。
public class abcMailTest {
public static void main(String[] args) {
String mailSmtpHost = "77.77.77.77";
String mailSmtpPort = "4321" ;
String mailTo = "avdq@abc.com";
//String mailCc = "avdg@abc.com ";
String mailFrom = "avdg@abc.com";
String mailSubject = "sgdtetrtrr";
String mailText = "Test Mail for mail body ";
sendEmail(mailTo, mailFrom, mailSubject, mailText, mailSmtpHost ,mailSmtpPort );
}
public static void sendEmail(String to, String from, String subject, String text, String smtpHost , String mailSmtpPort) {
try {
Properties properties = new Properties();
properties.put("mail.smtp.host", smtpHost);
properties.put("mailSmtpPort", mailSmtpPort);
//obtaining the session
Session emailSession = Session.getDefaultInstance(properties);
emailSession.setDebug(true);
//creating the message
Message emailMessage = new MimeMessage(emailSession);
emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
Address[] cc = new Address[] {
new InternetAddress("avdg@abc.com"),
new InternetAddress("sWER@gmail.com")};
emailMessage.addRecipients(Message.RecipientType.CC, cc);
emailMessage.setFrom(new InternetAddress(from));
emailMessage.setSubject(subject);
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(text, "text/html");
messageBodyPart.setText(text);
// Create a multipart message
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
MimeBodyPart attachPart = new MimeBodyPart();
String filename = "c:\\abc.pdf";
DataSource source = new FileDataSource(filename);
attachPart.setDataHandler(new DataHandler(source));
attachPart.setFileName(filename);
multipart.addBodyPart(attachPart);
// Send the complete message parts
emailMessage.setContent(multipart);
emailSession.setDebug(true);
Transport.send(emailMessage);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:4)
你只需要做与cc field
相同的事情Address[] to = new Address[] {InternetAddress.parse("avdq@abc.com"),
InternetAddress.parse("tvdq@abc.com"),
InternetAddress.parse("pvdq@abc.com")};
message.addRecipients(Message.RecipientType.TO, to);
答案 1 :(得分:1)
试试这个
String cc = "avdg@abc.com;sWER@gmail.com";
StringTokenizer st = new StringTokenizer(cc,":");
while(st.hasMoreTokens()) {
emailMessage.addRecipients(Message.RecipientType.CC, InternetAddress.parse(st.nextToken(),false);
}