javax.mail 发送邮件

来源:互联网 发布:程序员高薪 编辑:程序博客网 时间:2024/04/30 04:59
import java.io.IOException;import java.util.Properties;import javax.mail.Message;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;public class EmailSender {private static String host = "";private static String port = "";private static String user = "";private static String nickName = "";private static String password = "";private static String runKey = "";private static Properties properties=new Properties();static{try {properties.load(EmailSender.class.getClassLoader().getResourceAsStream("/email.properties"));host = properties.getProperty("host");user = properties.getProperty("user");nickName=properties.getProperty("nickName");password = properties.getProperty("password");port = properties.getProperty("port");runKey=properties.getProperty("runKey");} catch (IOException e) {System.out.println("the configuration file is not exist");e.printStackTrace();throw new RuntimeException(e);}}public static void send(String to, String subject, String content) {if(runKey.equals("0")){return;}Properties props = new Properties();props.put("mail.smtp.host", host);// 指定SMTP服务器props.put("mail.smtp.port", port);props.put("mail.smtp.auth", "true");// 指定是否需要SMTP验证try {Session mailSession = Session.getDefaultInstance(props);mailSession.setDebug(true);// 是否在控制台显示debug信息Message message = new MimeMessage(mailSession);message.setFrom(new InternetAddress(user,nickName));// 发件人message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));// 收件人message.setSubject(subject);// 邮件主题//message.setContent(content, "text/html;charset=utf-8");message.setText(content);// 邮件内容message.saveChanges();Transport transport = mailSession.getTransport("smtp");transport.connect(host, user, password);transport.sendMessage(message, message.getAllRecipients());transport.close();} catch (Exception e) {System.out.println(e);}}public static void main(String[] args) {send("111111@qq.com", "111111", "11111");}}


0 0
原创粉丝点击