1. You need to import the jar package: java.mail.jar (already in the attachment).
package test;
import java.util.Calendar;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendEmailTest {
public static void sendEmailMessage(String smtpHost, String fromEmail, String password, String toEmail, String subject, String messageText,
String messageType) throws MessagingException {
// 第一步:配置javax.mail.Session对象
System.out.println("as" + smtpHost + "configure mail session object");
Properties props = new Properties();
props.put("mail.smtp.host", smtpHost); props.put
("mail. smtp.starttls.enable", "true");// use STARTTLS secure connection
// props.put("mail.smtp.port", "25"); //google use port 465 or 587
props.put(" mail.smtp.auth", "true"); // use authentication
// props.put("mail.debug", "true");
Session mailSession = Session.getInstance(props, new MyAuthenticator(fromEmail, password)) ;
// Step 2: Write message
System.out.println("Write message from——to:" + fromEmail + "——" + toEmail);
InternetAddress fromAddress = new InternetAddress(fromEmail);
InternetAddress toAddress = new InternetAddress(toEmail);
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(fromAddress);
message.addRecipient(RecipientType.TO, toAddress);
message.setSentDate(Calendar.getInstance().getTime());
message.setSubject(subject);
message.setContent(messageText, messageType);
// 第三步:发送消息
Transport transport = mailSession.getTransport("smtp");
transport.connect(smtpHost, "", password);
transport.send(message, message.getRecipients(RecipientType.TO));
System.out.println("message send success!");
}
public static void main(String[] args) {
try {
SendEmailTest.sendEmailMessage("smtp.163.com", "[email protected]", "------", "[email protected]", "哈哈", "天道酬勤",
"text/html;charset=gb2312");
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class MyAuthenticator extends Authenticator {
String userName = "";
String password = "";
public MyAuthenticator() {
}
public MyAuthenticator(String userName, String password) {
this.userName = userName;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
}