java发送QQ邮件
程序员文章站
2022-03-30 13:47:19
...
java发送QQ邮件
<dependencies>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
</dependencies>
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class SendQQMailUtil {
public static void main(String[] args) throws MessagingException {
授权码
send("[email protected]", "xxx", "[email protected]", "hello", "hello i am you");
}
private static void send(String yourEmail, String shouQuanMa, String friendEmail, String EmailbiaoTi, String Emailmessage) throws MessagingException {
Properties properties = new Properties();
properties.put("mail.transport.protocol", "smtp");// 连接协议
properties.put("mail.smtp.host", "smtp.qq.com");// 主机名
properties.put("mail.smtp.port", 465);// 端口号
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.ssl.enable", "true");// 设置是否使用ssl安全连接 ---一般都使用
properties.put("mail.debug", "true");// 设置是否显示debug信息 true 会在控制台显示相关信息
// 得到回话对象
Session session = Session.getInstance(properties);
// 获取邮件对象
Message message = new MimeMessage(session);
// 设置发件人邮箱地址
message.setFrom(new InternetAddress(yourEmail));
// 设置收件人邮箱地址
//message.setRecipients(Message.RecipientType.TO, new InternetAddress[]{new InternetAddress("[email protected]"), new InternetAddress("[email protected]"), new InternetAddress("[email protected]")});
message.setRecipient(Message.RecipientType.TO, new InternetAddress(friendEmail));//一个收件人
// 设置邮件标题
message.setSubject(EmailbiaoTi);
// 设置邮件内容
message.setText(Emailmessage);
// 得到邮差对象
Transport transport = session.getTransport();
// 连接自己的邮箱账户
transport.connect(yourEmail, shouQuanMa);// 密码为QQ邮箱开通的stmp服务后得到的客户端授权码
// 发送邮件
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
}
上一篇: jsp template之我见