一段带SMTP认证的JAVAMAIL代码
类别: JSP教程
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
String mailNeedAuth = CatseyeConfig.getConfig("MailNeedAuth");
String mailUser = CatseyeConfig.getConfig("MailUser");
String mailPassword = CatseyeConfig.getConfig("MailPassword");
if (mailNeedAuth.equals("1")) {
props.put("mail.smtp.auth", "true");
} else {
props.put("mail.smtp.auth", "false");
}
Session session = Session.getDefaultInstance(props, null);
javax.mail.Message msg = new MimeMessage(session);
InternetAddress[] toAddrs = null;
try {
if (recipients != null) {
toAddrs = InternetAddress.parse(recipients, false);
msg.setRecipients(javax.mail.Message.RecipientType.TO, toAddrs);
} else {
throw new Exception("No recipient address specified");
}
if (sender != null) {
msg.setFrom(new InternetAddress(sender));
} else {
throw new Exception("No sender address specified");
}
if (subject != null) {
msg.setSubject(subject);
}
/*
BodyPart bp=new MimeBodyPart();
bp.setContent(body, "text/html");
Multipart mp=new MimeMultipart();
mp.addBodyPart(bp);
*/
//msg.setContent(mp);
msg.setContent(body, "text/html");
msg.setHeader("X-Mailer", "Catseye SMTP Robot");
msg.setHeader("Content-Type", "text/html");
/*
msg.setDataHandler(new DataHandler(
new ByteArrayDataSource(body, "text/html")));
//msg.setText(body);
*/
Transport trans = session.getTransport("smtp");
trans.connect(host, mailUser, mailPassword);
trans.sendMessage(msg,
msg.getRecipients(
javax.mail.Message.RecipientType.TO));
props.put("mail.smtp.host", host);
String mailNeedAuth = CatseyeConfig.getConfig("MailNeedAuth");
String mailUser = CatseyeConfig.getConfig("MailUser");
String mailPassword = CatseyeConfig.getConfig("MailPassword");
if (mailNeedAuth.equals("1")) {
props.put("mail.smtp.auth", "true");
} else {
props.put("mail.smtp.auth", "false");
}
Session session = Session.getDefaultInstance(props, null);
javax.mail.Message msg = new MimeMessage(session);
InternetAddress[] toAddrs = null;
try {
if (recipients != null) {
toAddrs = InternetAddress.parse(recipients, false);
msg.setRecipients(javax.mail.Message.RecipientType.TO, toAddrs);
} else {
throw new Exception("No recipient address specified");
}
if (sender != null) {
msg.setFrom(new InternetAddress(sender));
} else {
throw new Exception("No sender address specified");
}
if (subject != null) {
msg.setSubject(subject);
}
/*
BodyPart bp=new MimeBodyPart();
bp.setContent(body, "text/html");
Multipart mp=new MimeMultipart();
mp.addBodyPart(bp);
*/
//msg.setContent(mp);
msg.setContent(body, "text/html");
msg.setHeader("X-Mailer", "Catseye SMTP Robot");
msg.setHeader("Content-Type", "text/html");
/*
msg.setDataHandler(new DataHandler(
new ByteArrayDataSource(body, "text/html")));
//msg.setText(body);
*/
Transport trans = session.getTransport("smtp");
trans.connect(host, mailUser, mailPassword);
trans.sendMessage(msg,
msg.getRecipients(
javax.mail.Message.RecipientType.TO));
-= 资 源 教 程 =-
文 章 搜 索