编写发送邮件程序的时候,需要考虑到两个问题:
1、邮件发送者需要登录到邮件服务器,也就是需要进行认证。
2、发送邮件,需要考虑其邮件格式,是纯文本,还是html格式,采用什么编码。
下面是发送邮件的示例程序:
1、邮件认证类:
2、发送邮件的程序片段:
1、邮件发送者需要登录到邮件服务器,也就是需要进行认证。
2、发送邮件,需要考虑其邮件格式,是纯文本,还是html格式,采用什么编码。
下面是发送邮件的示例程序:
1、邮件认证类:
public class MailAuthenticator extends Authenticator {
String authenName; // 用户名
String authenPass; // 密码
public MailAuthenticator(String authenName, String authenPass) {
super();
this.authenName = authenName;
this.authenPass = authenPass;
}
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(authenName, authenPass);
}
}
2、发送邮件的程序片段:
public void sendMail( UserInfo user ) {
Authenticator ac = new MailAuthenticator( userName ,userPasswd );
Properties props = System.getProperties();
props.put("mail.smtp.host",host);
props.put("mail.smtp.auth","true"); /*服务器需要认证*/
Session session=Session.getInstance(props,ac); //Session会自动调用
try {
String content = getMailTemplate(user);
BodyPart mdp=new MimeBodyPart();//新建一个存放信件内容的BodyPart对象
mdp.setContent(content,"text/html;charset=gb2312");//给BodyPart对象设置内容和格式/编码方式
Multipart mm=new MimeMultipart();
mm.addBodyPart(mdp);//将BodyPart加入到MimeMultipart对象中(可以加入多个BodyPart)
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = { new InternetAddress( user.getEmail() ) };
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(SUBJECT);
msg.setSentDate(new Date());
msg.setText(content);
msg.setContent(mm);
Transport.send(msg);
} catch (MessagingException mex) {
mex.printStackTrace();
}
}