package sendmail; import javax.mail.Message; import javax.mail.Session; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import com.sun.mail.smtp.SMTPTransport; import java.io.FileOutputStream; import java.io.OutputStream; import java.util.Date; import java.util.Properties; public class sendmail { public static void main(String[] args) throws Exception { String from = "mbdkunkka@live.com"; String mailer = "mbdkunkka"; String password = "mypassword"; String to = "recvmailaddr@qq.com"; String subject = "机器故障,请及时处理"; String text = "机器与xx时间xx分钟收到重启信息"; String mailhost = "smtp.live.com"; String user = "mbdkunkka@live.com"; boolean auth = true; boolean debug = true,verbose =true; String prot = "smtp"; Properties props = System.getProperties(); if (mailhost != null) props.put("mail." + prot + ".host", mailhost); if (auth) props.put("mail." + prot + ".auth", "true"); Session session = Session.getInstance(props, null); if (debug) session.setDebug(true); Message msg = new MimeMessage(session); if (from != null) msg.setFrom(new InternetAddress(from)); else msg.setFrom(); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); msg.setSubject(subject); // setText(text, charset) msg.setText(text); msg.setHeader("X-Mailer", mailer); msg.setSentDate(new Date()); msg.setHeader("X-Mailer", mailer); msg.setSentDate(new Date()); SMTPTransport t = (SMTPTransport)session.getTransport(prot); try { if (auth) t.connect(mailhost, user, password); else t.connect(); t.sendMessage(msg, msg.getAllRecipients()); } finally { if (verbose) System.out.println("Response: " + t.getLastServerResponse()); t.close(); } System.out.println("\nMail was sent successfully."); } }
公共免费邮箱基本都不好用。基本都要加密的smtp地址。smtp的开通和密码要到网页邮箱中设置和获得。
原文:http://www.cnblogs.com/wxmcu/p/6388034.html