《Java Mail初探》
package intelligentfish; import java.util.Date; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.MimeMessage; /** * 利用Hotmail smtp 服务器发送邮件 * * @author intelligentfish */
//基于SSL的Mail登陆方式进行发送和接收电子邮件需要使用PasswordAuthentication对象
class MailAuthenticator extends Authenticator{ public MailAuthenticator(String userName, String password){ this.userName = userName; this.password = password; } protected PasswordAuthentication getPasswordAuthentication(){ return new PasswordAuthentication(userName, password); } private String userName; private String password; } public class Program { public static void main(String[] args) { String smtpHost = "smtp.live.com";//Hotmail smtp邮件服务器(端口25,也是smtp服务器的默认端口);SSL验证一般采用端口465 String to = "to-email-address";//邮件目的地址 String from = "from-email-address";//邮件源地址 Properties props = new Properties(); props.put("mail.transport.protocol", "smtp");//设置邮件协议 props.put("mail.smtp.socketFactory.port", 25);//设置邮件安全端口 props.put("mail.smtp.starttls.enable","true");//需要时使用SSL登陆方式 props.put("mail.smtp.auth", "true");//使用安全授权 props.put("mail.smtp.host", smtpHost);//设置邮件服务器 props.put("mail.from", from);//设置邮件源地址 Session session = Session.getInstance(props, new MailAuthenticator(from, "your password"));//获取邮件会话对象 session.setDebug(true);//启用调试信息 try { MimeMessage msg = new MimeMessage(session);//获取邮件消息对象 msg.setFrom();使用InternetAddress.getLocalAddress
方法设置RFC 822 "From" 头域 msg.setRecipients(Message.RecipientType.TO, to);//设置收件人 msg.setSubject("JavaMail hello world example");//设置邮件主题 msg.setSentDate(new Date());//设置邮件发送时间 msg.setText("Hello, world!\n");//设置邮件内容 Transport.send(msg);//发送邮件 } catch (MessagingException mex) { System.out.println("send failed, exception: " + mex); } } }