邮件发送者设置setFrom(new InternetAddress(from))完全不起作用, google默认用username = "***@gmail.com"作为发送者显示。
/* 以下是在一个国外论坛上找到的代码 */
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.apache.log4j.Logger;
public class MailUtil {
private String from;
private String to;
private String subject;
private String body;
private String[] myfile;
public void sendMail() throws Exception {
String host = "smtp.gmail.com";
// Create properties, get Session
Properties props = new Properties();
// If using static Transport.send(),
// need to specify which host to send it to
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.port","587");
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
// To see what is going on behind the scene
props.put("mail.debug", "true");
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
// Instantiatee a message
Message msg = new MimeMessage(session);
// Set message attributes
msg.setFrom(new InternetAddress(from));
// InternetAddress[] address = { new InternetAddress(to) };
InternetAddress[] address = InternetAddress.parse(to);
InternetAddress[] address = InternetAddress.parse(to);
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
msg.setSentDate(new Date());
// create the message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
//fill message
messageBodyPart.setContent(content, "text/html;charset=utf-8");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
for (int i = 0; i < myfile.length; i++) {
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(myfile[i]);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(myfile[i]);
multipart.addBodyPart(messageBodyPart);
}
// Put parts in message
msg.setContent(multipart);
// Send the message
logger.info("preparing to send<br>");
Transport.send(msg);
}
public void setFrom(String from) {
this.from = from;
}
public void setTo(String to) {
this.to = to;
}
public void setSubject(String subject) {
this.subject = subject;
}
public void setBody(String body) {
this.body = body;
}
public void setMyfile(String[] myfile) {
this.myfile = myfile;
}
}
class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
String username = "***@gmail.com";
String password = "******";
return new PasswordAuthentication(username, password);
}
}