我有以下代码,可以从gmail发送邮件。问题是我应该在哪个部分添加CC和BCC接收器,以便他们也可以接收邮件。
我做了一个搜索并在这里找到了一些帮助,但它对我的程序没有用,我在BCC和CC列表上收到错误。
InternetAddress[] myToList = InternetAddress.parse("gopi.mani@xyz.com,Maimsa.SF@xyz.com"); InternetAddress[] myBccList = InternetAddress.parse("Usha.B@xyz.com"); InternetAddress[] myCcList = InternetAddress.parse("NEHA.SIVA@xyz.com"); message.setRecipients(Message.RecipientType.TO,myToList); message.addRecipient(Message.RecipientType.BCC,myBccList); message.addRecipient(Message.RecipientType.CC,myCcList);
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class SendEmail {
private static final String SMTP_HOST_NAME = "smtp.gmail.com";
private static final int SMTP_HOST_PORT = 587;
private static final String SMTP_AUTH_USER = "sender@gmail.com";
private static final String SMTP_AUTH_PWD = "";
public static void main(String[] args) throws Exception {
SendEmail se = new SendEmail();
se.mail();
}
public void mail() throws Exception {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session mailSession = Session.getDefaultInstance(props);
mailSession.setDebug(true);
Transport transport = mailSession.getTransport();
MimeMessage message = new MimeMessage(mailSession);
message.setSubject("Testing SMTP From Java");
message.setContent("Hello world", "text/plain");
message.addRecipient(Message.RecipientType.TO, new InternetAddress("receiver@gmail.com"));
transport.connect(SMTP_HOST_NAME, SMTP_HOST_PORT, SMTP_AUTH_USER, SMTP_AUTH_PWD);
transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
transport.close();
}
}
答案 0 :(得分:2)
变化:
message.setRecipients(Message.RecipientType.TO,myToList);
为:
message.addRecipients(Message.RecipientType.TO,myToList);
然后:
transport.sendMessage(message, message.getAllRecipients());
答案 1 :(得分:0)
不是直接的答案,但这可以帮助您采取不同的方法。 我是公共电子邮箱的粉丝:http://commons.apache.org/proper/commons-email/
您可以发送这样的电子邮件,这样可以更直接地阅读。
Email email = new SimpleEmail();
email.setHostName("smtp.googlemail.com");
email.setSmtpPort(465);
email.setAuthenticator(new DefaultAuthenticator("username", "password"));
email.setSSLOnConnect(true);
email.setFrom("user@gmail.com");
email.setSubject("TestMail");
email.setMsg("This is a test mail ... :-)");
email.addTo("foo@bar.com");
email.send();
-Rick