记录一段用过的代码,方便以后备查。
需要用到的jar包为:mail.jar、activation.jar
可到如下位置下载:
http://java.sun.com/products/javamail/downloads/index.html
http://java.sun.com/products/javabeans/jaf/downloads/index.html
代码示例如下:
需要用到的jar包为:mail.jar、activation.jar
可到如下位置下载:
http://java.sun.com/products/javamail/downloads/index.html
http://java.sun.com/products/javabeans/jaf/downloads/index.html
代码示例如下:
package com.JavaMail;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.apache.log4j.Logger;
public class MailServices {
Logger log = Logger.getLogger(MailServices.class.getName());
public void sendMail(String mailTitle, String receiveAddress,
String sendAddress, String userName, String password,
String serverSMTP) {
String title = mailTitle;
String serverSmtp = serverSMTP;// 10.3.7.10
try {
title = new String(title.getBytes("GBK"));
} catch (UnsupportedEncodingException e) {
log.error("邮件发送时出现异常", e);
}
Properties props = new Properties();
props.put("mail.smtp.host", serverSmtp);
props.put("mail.smtp.auth", "true");//不输出debug信息
Session mailSession = Session.getDefaultInstance(props);
mailSession.setDebug(true);//是否在控制台显示debug信息
Message message = new MimeMessage(mailSession);
try {
message.setFrom(new InternetAddress(sendAddress));//发件人
message.addRecipient(Message.RecipientType.TO, new InternetAddress(
receiveAddress));// 收件人guo.yj@cppims.com
message.setSubject(title);//设置标题
message.setText(title);//邮件内容
message.saveChanges();
} catch (AddressException e) {
log.error("邮件地址配置有误!", e);
} catch (MessagingException e) {
log.error("邮件配置时出现异常!", e);
}
try {
Transport transport = mailSession.getTransport("smtp");
transport.connect(serverSmtp, userName, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
log.info("邮件发送成功!");
} catch (NoSuchProviderException e) {
log.error("邮件发送时出现异常!", e);
} catch (MessagingException e) {
log.error("邮件发送时出现异常!", e);
}
}
public static void main(String []args){
MailServices ms = new MailServices();
//ms.sendMail();
}
}