使用Javamail发送邮件,必需的jar包(请下载javamail的源文件):
- mailapi.jar。定义了收发邮件所使用到的接口API;
- smtp.jar。包含了发送邮件使用到的类;
- pop3.jar。包含了收邮件使用到的类;
我们通常发送邮件使用的协议是smtp协议,接受邮件使用的协议是pop3协议。或者,我们直接将mail.jar加入到工程,这个jar包里边包含了java收发邮件所有的接口和类。
常用的类:
javax.mail.Session; -------->保存连接服务器所需要的信息;
javax.mail.Message; -------->邮件体,保存邮件的内容;
javax.mail.Transport; -------->发送邮件的载体
javax.mail.internet.InternetAddress; -------->邮件的地址信息
下边,我先列出使用Java发送邮件的最简单的一个小测试示例:
- import java.util.Properties;
- import javax.mail.Address;
- import javax.mail.Message;
- import javax.mail.MessagingException;
- import javax.mail.Session;
- import javax.mail.Transport;
- import javax.mail.internet.InternetAddress;
- import javax.mail.internet.MimeMessage;
- /**
- *
- * @author Champion Wong
- *
- * QQ(mail.qq.com):POP3服务器(端口995)SMTP服务器(端口465或587)。
- *
- */
- public class Demo1 {
- /**
- * @param args
- * @throws MessagingException
- */
- public static void main(String[] args) throws MessagingException {
- String sendUserName = "XXX@126.com";
- String sendPassword = "pwd"; 密码这个地方需要留意:不是网页邮箱登录密码,而是客户的授权密码,见末尾示例图。
- Properties properties = new Properties();
- properties.setProperty("mail.smtp.auth", "true");//服务器需要认证
- properties.setProperty("mail.transport.protocol", "smtp");//声明发送邮件使用的端口
- Session session = Session.getInstance(properties);
- session.setDebug(true);//同意在当前线程的控制台打印与服务器对话信息
- Message message = new MimeMessage(session);//构建发送的信息
- message.setText("你好,我是Champion.Wong!");//信息内容
- message.setFrom(new InternetAddress("XXX@126.com"));//发件人
- Transport transport = session.getTransport();
- transport.connect("smtp.126.com", 25, sendUserName, sendPassword);//连接发件人使用发件的服务器
- transport.sendMessage(message, new Address[]{new InternetAddress("XXXX@qq.com")});//接受邮件
- transport.close();
- }
- }
一般的,我们使用Authenticator把用户名和密码封装起来,不透明!所以:
- 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.AddressException;
- import javax.mail.internet.InternetAddress;
- import javax.mail.internet.MimeMessage;
- import junit.framework.TestCase;
- /**
- * javamail 发送邮件
- * @author Champion Wong
- * Message.addRecipient(Message.Recipient recipient, Address address); 发邮件的时候指定收件人和收件人的角色
- * Message.RecipientType.TO 收件人
- * Message.RecipientType.CC 抄送,即发邮件的时候顺便给另一个人抄一份,不用回复!但是,上边的收件人可以看到你都抄送给了谁
- * Message.RecipientType.BCC 暗送,也是发邮件的时候顺便给另一个人暗发一份,但是,不同于上边的是,收件人不能看到你都暗送给了谁
- *
- */
- public class Demo2 extends TestCase {
- private static final String sendUserName = "XXX@126.com";// 发送邮件需要连接的服务器的用户名
- private static final String sendPassword = "pwd";// 发送邮件需要连接的服务器的密码
- private static final String sendProtocol = "smtp";// 发送邮件使用的端口
- private static final String sendHostAddress = "smtp.126.com";// 发送邮件使用的服务器的地址
- public void test() throws AddressException, MessagingException {
- Properties properties = new Properties();
- properties.setProperty("mail.smtp.auth", "true");// 服务器需要认证
- properties.setProperty("mail.transport.protocol", sendProtocol);// 声明发送邮件使用的端口
- properties.setProperty("mail.host", sendHostAddress);// 发送邮件的服务器地址
- Session session = Session.getInstance(properties, new Authenticator() {
- protected PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication(sendUserName, sendPassword);
- }
- });
- session.setDebug(true);//在后台打印发送邮件的实时信息
- Message message = new MimeMessage(session);
- message.setFrom(new InternetAddress("XXX@126.com"));
- message.setSubject("Demo2JavaCode发送邮件测试,采用Authenticator");// 设置主题
- message.setRecipients(Message.RecipientType.TO, InternetAddress
- .parse("XXX@qq.com,XXX@126.com"));// 发送
- message.setRecipients(Message.RecipientType.CC, InternetAddress
- .parse("XXX@hotmail.com"));// 抄送
- message
- .setContent(
- "<span style="font-size:20px; color:#FFCCFF" mce_style="font-size:20px; color:#FFCCFF">如果您看到,证明测试成功了!</span>",
- "text/html;charset=gbk");
- Transport.send(message);//发送邮件
- }
- }
我们发送一个比较复杂的邮件,包括附件,图文:
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.OutputStream;
- import java.util.Properties;
- import javax.activation.DataHandler;
- import javax.activation.DataSource;
- import javax.activation.FileDataSource;
- import javax.mail.Authenticator;
- import javax.mail.MessagingException;
- import javax.mail.PasswordAuthentication;
- import javax.mail.Session;
- import javax.mail.Transport;
- import javax.mail.Message.RecipientType;
- import javax.mail.internet.InternetAddress;
- import javax.mail.internet.MimeBodyPart;
- import javax.mail.internet.MimeMessage;
- import javax.mail.internet.MimeMultipart;
- import javax.mail.internet.MimeUtility;
- /**
- *
- * @author Administrator Mr XP.Wang
- * MimeMultipart 一般电子邮件的容器是Multipart,定义了增加及删除电子邮件各部分内容的方法,
- * 但是其是抽象类,需要其子类MimeMultipart来时用MimeMessage对象
- * MimeBodyPart 是BodyPart具体用于mimeMessage的一个子类,MimeBodyPart对象代表一个
- * mimeMultipart对象的每一个部分
- * MimeUtility.encodeText(String cn)用于解决邮件中的头部信息中中文的乱码问题
- *
- */
- public class Demo3_test {
- public static void main(String[] args) throws Exception {
- Properties properties = new Properties();
- properties.setProperty("mail.smtp.auth", "true");// 服务器需要认证
- properties.setProperty("mail.transport.protocol", "smtp");// 声明发送邮件使用的端口
- properties.setProperty("mail.host", "smtp.126.com");// 发送邮件的服务器地址
- Session session = Session.getInstance(properties, new Authenticator() {
- String sendUserName = "XXX@126.com";
- String sendPassword = "pwd";
- protected PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication(sendUserName,
- sendPassword);
- }
- });
- session.setDebug(true);
- MimeMessage msg = new MimeMessage(session);// 声明一个邮件体
- msg.setFrom(new InternetAddress("/""+MimeUtility.encodeText("Mr XP.Wang")+"/"<XXX@126.com>"));
- msg.setSubject("这是我的第一份复杂邮件");//设置邮件主题
- msg.setRecipients(MimeMessage.RecipientType.TO, InternetAddress.parse(MimeUtility.encodeText("姓名")+"<XXX@126.com>,"+MimeUtility.encodeText("三毛")+"<XXX@qq.com>"));
- MimeMultipart msgMultipart = new MimeMultipart("mixed");// 标明邮件的组合关系,混合的关系
- msg.setContent(msgMultipart);// 设置邮件体
- MimeBodyPart attch1 = new MimeBodyPart();// 附件1
- MimeBodyPart attch2 = new MimeBodyPart();// 附件2
- MimeBodyPart content = new MimeBodyPart();// 邮件的正文,混合体(图片+文字)
- // 将附件和正文设置到这个邮件体中
- msgMultipart.addBodyPart(attch1);
- msgMultipart.addBodyPart(attch2);
- msgMultipart.addBodyPart(content);
- // 设置第一个附件
- DataSource ds1 = new FileDataSource("F:/ACCP5.0/文件/ssh配置.txt");// 指定附件的数据源
- DataHandler dh1 = new DataHandler(ds1);// 附件的信息
- attch1.setDataHandler(dh1);// 指定附件
- attch1.setFileName("ssh.txt");
- // 设置第二个附件
- DataSource ds2 = new FileDataSource("resource/48.jpg");// 指定附件的数据源
- DataHandler dh2 = new DataHandler(ds2);// 附件的信息
- attch2.setDataHandler(dh2);// 指定附件
- attch2.setFileName("48.jpg");
- //设置邮件的正文
- MimeMultipart bodyMultipart = new MimeMultipart("related");//依赖关系
- content.setContent(bodyMultipart);//指定正文
- MimeBodyPart htmlPart = new MimeBodyPart();
- MimeBodyPart gifPart = new MimeBodyPart();
- bodyMultipart.addBodyPart(htmlPart);
- bodyMultipart.addBodyPart(gifPart);
- DataSource gifds = new FileDataSource("resource/48.jpg");//正文的图片
- DataHandler gifdh = new DataHandler(gifds);
- gifPart.setHeader("Content-Location", "http://mimg.126.net/logo/126logo.gif");
- gifPart.setDataHandler(gifdh);//设置正文的图片
- htmlPart.setContent("我只是来打酱油的,这是我的形象照!<img src="/" mce_src="/""http://mimg.126.net/logo/126logo.gif/">", "text/html;charset=gbk");//设置正文文字
- msg.saveChanges();//保存邮件
- //将邮件保存成文件
- OutputStream ops = new FileOutputStream("C:/Users/Administrator/Desktop/test.eml");
- msg.writeTo(ops);
- ops.close();
- Transport.send(msg);
- }
- }
JAVA MAIL 配置项详细说明:
Name Type Description
mail.smtp.user | String | Default user name for SMTP. |
mail.smtp.host | String | The SMTP server to connect to. |
mail.smtp.port | int | The SMTP server port to connect to, if the connect() method doesn't explicitly specify one. Defaults to 25. |
mail.smtp.connectiontimeout | int | Socket connection timeout value in milliseconds. Default is infinite timeout. |
mail.smtp.timeout | int | Socket I/O timeout value in milliseconds. Default is infinite timeout. |
mail.smtp.from | String | Email address to use for SMTP MAIL command. This sets the envelope return address. Defaults to msg.getFrom() or InternetAddress.getLocalAddress(). NOTE: mail.smtp.user was previously used for this. |
mail.smtp.localhost | String | Local host name used in the SMTP HELO or EHLO command. Defaults to |
mail.smtp.localaddress | String | Local address (host name) to bind to when creating the SMTP socket. Defaults to the address picked by the Socket class. Should not normally need to be set, but useful with multi-homed hosts where it's important to pick a particular local address to bind to. |
mail.smtp.localport | int | Local port number to bind to when creating the SMTP socket. Defaults to the port number picked by the Socket class. |
mail.smtp.ehlo | boolean | If false, do not attempt to sign on with the EHLO command. Defaults to true. Normally failure of the EHLO command will fallback to the HELO command; this property exists only for servers that don't fail EHLO properly or don't implement EHLO properly. |
mail.smtp.auth | boolean | If true, attempt to authenticate the user using the AUTH command. Defaults to false. |
mail.smtp.auth.mechanisms | String | If set, lists the authentication mechanisms to consider, and the order in which to consider them. Only mechanisms supported by the server and supported by the current implementation will be used. The default is |
mail.smtp.submitter | String | The submitter to use in the AUTH tag in the MAIL FROM command. Typically used by a mail relay to pass along information about the original submitter of the message. See also the |
mail.smtp.dsn.notify | String | The NOTIFY option to the RCPT command. Either NEVER, or some combination of SUCCESS, FAILURE, and DELAY (separated by commas). |
mail.smtp.dsn.ret | String | The RET option to the MAIL command. Either FULL or HDRS. |
mail.smtp.allow8bitmime | boolean | If set to true, and the server supports the 8BITMIME extension, text parts of messages that use the "quoted-printable" or "base64" encodings are converted to use "8bit" encoding if they follow the RFC2045 rules for 8bit text. |
mail.smtp.sendpartial | boolean | If set to true, and a message has some valid and some invalid addresses, send the message anyway, reporting the partial failure with a SendFailedException. If set to false (the default), the message is not sent to any of the recipients if there is an invalid recipient address. |
mail.smtp.sasl.realm | String | The realm to use with DIGEST-MD5 authentication. |
mail.smtp.quitwait | boolean | If set to false, the QUIT command is sent and the connection is immediately closed. If set to true (the default), causes the transport to wait for the response to the QUIT command. |
mail.smtp.reportsuccess | boolean | If set to true, causes the transport to include an |
mail.smtp.socketFactory | SocketFactory | If set to a class that implements the |
mail.smtp.socketFactory.class | String | If set, specifies the name of a class that implements the |
mail.smtp.socketFactory.fallback | boolean | If set to true, failure to create a socket using the specified socket factory class will cause the socket to be created using the |
mail.smtp.socketFactory.port | int | Specifies the port to connect to when using the specified socket factory. If not set, the default port will be used. |
mail.smtp.ssl.enable | boolean | If set to true, use SSL to connect and use the SSL port by default. Defaults to false for the "smtp" protocol and true for the "smtps" protocol. |
mail.smtp.ssl.checkserveridentity | boolean | If set to true, check the server identity as specified by RFC 2595 . These additional checks based on the content of the server's certificate are intended to prevent man-in-the-middle attacks. Defaults to false. |
mail.smtp.ssl.socketFactory | SSLSocketFactory | If set to a class that extends the |
mail.smtp.ssl.socketFactory.class | String | If set, specifies the name of a class that extends the |
mail.smtp.ssl.socketFactory.port | int | Specifies the port to connect to when using the specified socket factory. If not set, the default port will be used. |
mail.smtp.ssl.protocols | string | Specifies the SSL protocols that will be enabled for SSL connections. The property value is a whitespace separated list of tokens acceptable to the |
mail.smtp.ssl.ciphersuites | string | Specifies the SSL cipher suites that will be enabled for SSL connections. The property value is a whitespace separated list of tokens acceptable to the |
mail.smtp.mailextension | String | Extension string to append to the MAIL command. The extension string can be used to specify standard SMTP service extensions as well as vendor-specific extensions. Typically the application should use the |
mail.smtp.starttls.enable | boolean | If true, enables the use of the |
mail.smtp.starttls.required | boolean | If true, requires the use of the |
mail.smtp.userset | boolean | If set to true, use the RSET command instead of the NOOP command in the |