Java mail邮件小程序

package com.mail;

import javax.mail.Message;
import javax.mail.Transport;
import javax.mail.Session;

import java.util.Properties;

import javax.mail.internet.MimeMessage;
import javax.mail.internet.InternetAddress;
import javax.mail.MessagingException;

public class send {
public static void main(String[] args) throws Exception {
new send().sendMail();
}

private String host = "smtp.sina.com";// 主机;
private String user = "username";// 用户名;
private String password = "password";// 密码;
private String from = "[email protected]";// 发件人;
private String to = "[email protected]";// 收件人;
private String subjetc = "注册成功提示";// 标题;
private String content = "尊敬的用户,你已经注册成功,点此确认!";// 内容;

/**
* 发送email
*
* @throws MessagingException
* @throws Exception
*/
public void sendMail() throws MessagingException, Exception {
Properties props = new Properties();

props.put("mail.smtp.host", host);// 指定SMTP服务器
props.put("mail.smtp.auth", "true");// 指定是否需要SMTP验证

Session mailSession = Session.getDefaultInstance(props);
Message message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(from));// 发件人
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));// 收件人

message.setSubject(subjetc);// 邮件主题
message.setText(content);// 邮件内容
message.saveChanges();

Transport transport = mailSession.getTransport("smtp");
transport.connect(host, user, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}

}

你可能感兴趣的:(Java mail邮件小程序)