展开全部
一个小例e69da5e6ba903231313335323631343130323136353331333363376535子,也可使用其他apiimport java.util.Properties;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
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 Test {
// test
public static void main(String[] args) throws Exception {
sendEmail("smtp.163.com", "测试", "测试", "!!!收件人地址!!!", "!!!发件人邮箱用户名!!!", "!!!邮箱密码!!!", "发件人昵称");
}
/**
*
* @param smtp
* @throws Exception
*/
public static void sendEmail(String emailServer, String subject, String mailBody, String receiver, final String username, final String password, String nickname) throws Exception {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.smtp.host", emailServer);
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
Session session = Session.getDefaultInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
session.setDebug(true);
MimeMessage mimeMsg = new MimeMessage(session);
Multipart mp = new MimeMultipart();
mimeMsg.setSubject(MimeUtility.encodeText(subject, "utf-8", null));
nickname = MimeUtility.encodeText(nickname, "utf-8", null);
mimeMsg.setFrom(new InternetAddress(username, nickname, "UTF-8"));
BodyPart bp = new MimeBodyPart();
bp.setContent(mailBody, "text/html;charset=utf-8");
mp.addBodyPart(bp);
mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiver));
mimeMsg.setContent(mp);
mimeMsg.saveChanges();
Transport transport = session.getTransport();
transport.connect(username, password);
Address[] allRecipients = mimeMsg.getAllRecipients();
transport.sendMessage(mimeMsg, allRecipients);
transport.close();
}
}