Java发送邮件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java发送邮件相关的知识,希望对你有一定的参考价值。
2017-03-07
首先需要导入javax.mail.jar包,下载地址为https://java.net/projects/javamail/pages/Home
163邮箱需要打开客户端授权码
import java.util.Properties; import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMessage.RecipientType; public class Email { public static void main(String[] args) throws Exception { Properties props = new Properties(); props.setProperty("mail.host", "smtp.163.com");//设置发送主机 props.setProperty("mail.smtp.auth", "true");// 设置是否需要验证 Authenticator auth = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("hfutlj", "********");//密码为163客户端授权码,不是登录密码 } }; Session session = Session.getInstance(props, auth); MimeMessage message = new MimeMessage(session); String nick = ""; nick = javax.mail.internet.MimeUtility.encodeText("张三");//昵称的处理,否则为乱码 message.setFrom(new InternetAddress(nick + "<[email protected]>")); message.setRecipient(RecipientType.TO, new InternetAddress("[email protected]")); message.setRecipient(RecipientType.CC, new InternetAddress("[email protected]")); message.setSubject("测试邮件"); message.setContent("注意正文和标题部分不能写test、helloword等否则会被163视为垃圾邮件,报534错误", "text/html;charset=utf-8"); Transport.send(message); } }
以上是关于Java发送邮件的主要内容,如果未能解决你的问题,请参考以下文章