package email;
import java.io.File;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
public class EmailTest {
public static String myEmailAccount = "xxxxxxxx01@126.com";
public static String myEmailPassword = "xxxxxxxx01";
public static String myEmailSMTPHost = "smtp.126.com";
public static String receiveMailAccount = "xxxxxxxx@qq.com,xxxxxxxxx01@126.com";
public static void main(String[] args) throws Exception {
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", myEmailSMTPHost);
props.setProperty("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
session.setDebug(true);
MimeMessage message = createMimeMessage(session, myEmailAccount, receiveMailAccount);
Transport transport = session.getTransport();
transport.connect(myEmailAccount, myEmailPassword);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
private static MimeMessage createMimeMessage(Session session,
String sendMail, String receiveMail) throws Exception {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(sendMail, "京东", "UTF-8"));
// message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "XX用户", "UTF-8"));
InternetAddress[] toAddr = InternetAddress.parse(receiveMail);
message.addRecipients(MimeMessage.RecipientType.TO, toAddr);
message.setSubject("xxxxx", "UTF-8");
// 5. Content: 邮件正文(可以使用html标签)
Multipart multipart = new MimeMultipart();
MimeBodyPart contentPart = new MimeBodyPart();
contentPart.setText("XX用户你好。。。");
multipart.addBodyPart(contentPart);
MimeBodyPart attachmentPart = new MimeBodyPart();
File file = new File("D://WindV.txt");
FileDataSource source = new FileDataSource(file);
attachmentPart.setDataHandler(new DataHandler(source));
attachmentPart.setFileName(MimeUtility.encodeWord(file.getName(), "gb2312", null));
multipart.addBodyPart(attachmentPart);
message.setContent(multipart);
message.setSentDate(new Date());
message.saveChanges();
return message;
}
}