javaMail发送电子邮件

使用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发送邮件的最简单的一个小测试示例:

 

[java]  view plain copy
  1. import java.util.Properties;  
  2.   
  3. import javax.mail.Address;  
  4. import javax.mail.Message;  
  5. import javax.mail.MessagingException;  
  6. import javax.mail.Session;  
  7. import javax.mail.Transport;  
  8. import javax.mail.internet.InternetAddress;  
  9. import javax.mail.internet.MimeMessage;  
  10.   
  11. /** 
  12.  *  
  13.  * @author Champion Wong 
  14.  *  
  15.  * QQ(mail.qq.com):POP3服务器(端口995)SMTP服务器(端口465或587)。 
  16.  * 
  17.  */  
  18. public class Demo1 {  
  19.   
  20.     /** 
  21.      * @param args 
  22.      * @throws MessagingException  
  23.      */  
  24.     public static void main(String[] args) throws MessagingException {  
  25.           
  26.         String sendUserName = "XXX@126.com";  
  27.         String sendPassword = "pwd";  密码这个地方需要留意:不是网页邮箱登录密码,而是客户的授权密码,见末尾示例图。
  28.           
  29.         Properties properties = new Properties();  
  30.         properties.setProperty("mail.smtp.auth""true");//服务器需要认证  
  31.         properties.setProperty("mail.transport.protocol""smtp");//声明发送邮件使用的端口  
  32.           
  33.         Session session = Session.getInstance(properties);  
  34.         session.setDebug(true);//同意在当前线程的控制台打印与服务器对话信息  
  35.           
  36.         Message message = new MimeMessage(session);//构建发送的信息  
  37.         message.setText("你好,我是Champion.Wong!");//信息内容  
  38.         message.setFrom(new InternetAddress("XXX@126.com"));//发件人  
  39.           
  40.         Transport transport = session.getTransport();  
  41.         transport.connect("smtp.126.com"25, sendUserName, sendPassword);//连接发件人使用发件的服务器  
  42.         transport.sendMessage(message, new Address[]{new InternetAddress("XXXX@qq.com")});//接受邮件  
  43.         transport.close();  
  44.     }  
  45.   
  46. }  

 

 

一般的,我们使用Authenticator把用户名和密码封装起来,不透明!所以:

 

[java]  view plain copy
  1. import javax.mail.Authenticator;  
  2. import javax.mail.Message;  
  3. import javax.mail.MessagingException;  
  4. import javax.mail.PasswordAuthentication;  
  5. import javax.mail.Session;  
  6. import javax.mail.Transport;  
  7. import javax.mail.internet.AddressException;  
  8. import javax.mail.internet.InternetAddress;  
  9. import javax.mail.internet.MimeMessage;  
  10.   
  11. import junit.framework.TestCase;  
  12.   
  13. /** 
  14.  * javamail 发送邮件 
  15.  * @author Champion Wong 
  16.  * Message.addRecipient(Message.Recipient recipient, Address address); 发邮件的时候指定收件人和收件人的角色 
  17.  * Message.RecipientType.TO 收件人 
  18.  * Message.RecipientType.CC 抄送,即发邮件的时候顺便给另一个人抄一份,不用回复!但是,上边的收件人可以看到你都抄送给了谁 
  19.  * Message.RecipientType.BCC 暗送,也是发邮件的时候顺便给另一个人暗发一份,但是,不同于上边的是,收件人不能看到你都暗送给了谁 
  20.  * 
  21.  */  
  22. public class Demo2 extends TestCase {  
  23.   
  24.     private static final String sendUserName = "XXX@126.com";// 发送邮件需要连接的服务器的用户名  
  25.   
  26.     private static final String sendPassword = "pwd";// 发送邮件需要连接的服务器的密码  
  27.   
  28.     private static final String sendProtocol = "smtp";// 发送邮件使用的端口  
  29.   
  30.     private static final String sendHostAddress = "smtp.126.com";// 发送邮件使用的服务器的地址  
  31.   
  32.     public void test() throws AddressException, MessagingException {  
  33.   
  34.         Properties properties = new Properties();  
  35.         properties.setProperty("mail.smtp.auth""true");// 服务器需要认证  
  36.         properties.setProperty("mail.transport.protocol", sendProtocol);// 声明发送邮件使用的端口  
  37.         properties.setProperty("mail.host", sendHostAddress);// 发送邮件的服务器地址  
  38.   
  39.         Session session = Session.getInstance(properties, new Authenticator() {  
  40.             protected PasswordAuthentication getPasswordAuthentication() {  
  41.                 return new PasswordAuthentication(sendUserName, sendPassword);  
  42.             }  
  43.         });  
  44.         session.setDebug(true);//在后台打印发送邮件的实时信息  
  45.   
  46.         Message message = new MimeMessage(session);  
  47.         message.setFrom(new InternetAddress("XXX@126.com"));  
  48.         message.setSubject("Demo2JavaCode发送邮件测试,采用Authenticator");// 设置主题  
  49.         message.setRecipients(Message.RecipientType.TO, InternetAddress  
  50.                 .parse("XXX@qq.com,XXX@126.com"));// 发送  
  51.         message.setRecipients(Message.RecipientType.CC, InternetAddress  
  52.                 .parse("XXX@hotmail.com"));// 抄送  
  53.         message  
  54.                 .setContent(  
  55.                         "<span style="font-size:20px; color:#FFCCFF" mce_style="font-size:20px; color:#FFCCFF">如果您看到,证明测试成功了!</span>",  
  56.                         "text/html;charset=gbk");  
  57.   
  58.         Transport.send(message);//发送邮件  
  59.     }  
  60. }  

 

 

我们发送一个比较复杂的邮件,包括附件,图文:

 

[java]  view plain copy
  1. import java.io.FileNotFoundException;  
  2. import java.io.FileOutputStream;  
  3. import java.io.IOException;  
  4. import java.io.OutputStream;  
  5. import java.util.Properties;  
  6.   
  7. import javax.activation.DataHandler;  
  8. import javax.activation.DataSource;  
  9. import javax.activation.FileDataSource;  
  10. import javax.mail.Authenticator;  
  11. import javax.mail.MessagingException;  
  12. import javax.mail.PasswordAuthentication;  
  13. import javax.mail.Session;  
  14. import javax.mail.Transport;  
  15. import javax.mail.Message.RecipientType;  
  16. import javax.mail.internet.InternetAddress;  
  17. import javax.mail.internet.MimeBodyPart;  
  18. import javax.mail.internet.MimeMessage;  
  19. import javax.mail.internet.MimeMultipart;  
  20. import javax.mail.internet.MimeUtility;  
  21.   
  22. /** 
  23.  *  
  24.  * @author Administrator Mr XP.Wang  
  25.  * MimeMultipart 一般电子邮件的容器是Multipart,定义了增加及删除电子邮件各部分内容的方法,  
  26.  *               但是其是抽象类,需要其子类MimeMultipart来时用MimeMessage对象 
  27.  * MimeBodyPart 是BodyPart具体用于mimeMessage的一个子类,MimeBodyPart对象代表一个 
  28.  *              mimeMultipart对象的每一个部分 
  29.  * MimeUtility.encodeText(String cn)用于解决邮件中的头部信息中中文的乱码问题 
  30.  *  
  31.  */  
  32. public class Demo3_test {  
  33.   
  34.     public static void main(String[] args) throws Exception {  
  35.           
  36.         Properties properties = new Properties();  
  37.         properties.setProperty("mail.smtp.auth""true");// 服务器需要认证  
  38.         properties.setProperty("mail.transport.protocol""smtp");// 声明发送邮件使用的端口  
  39.         properties.setProperty("mail.host""smtp.126.com");// 发送邮件的服务器地址  
  40.           
  41.         Session session = Session.getInstance(properties, new Authenticator() {  
  42.             String sendUserName = "XXX@126.com";  
  43.             String sendPassword = "pwd";  
  44.             protected PasswordAuthentication getPasswordAuthentication() {  
  45.                 return new PasswordAuthentication(sendUserName,  
  46.                         sendPassword);  
  47.             }  
  48.         });  
  49.         session.setDebug(true);  
  50.           
  51.         MimeMessage msg = new MimeMessage(session);// 声明一个邮件体  
  52.         msg.setFrom(new InternetAddress("/""+MimeUtility.encodeText("Mr XP.Wang")+"/"<XXX@126.com>"));  
  53.         msg.setSubject("这是我的第一份复杂邮件");//设置邮件主题  
  54.         msg.setRecipients(MimeMessage.RecipientType.TO, InternetAddress.parse(MimeUtility.encodeText("姓名")+"<XXX@126.com>,"+MimeUtility.encodeText("三毛")+"<XXX@qq.com>"));  
  55.   
  56.         MimeMultipart msgMultipart = new MimeMultipart("mixed");// 标明邮件的组合关系,混合的关系  
  57.         msg.setContent(msgMultipart);// 设置邮件体  
  58.           
  59.   
  60.         MimeBodyPart attch1 = new MimeBodyPart();// 附件1  
  61.         MimeBodyPart attch2 = new MimeBodyPart();// 附件2  
  62.         MimeBodyPart content = new MimeBodyPart();// 邮件的正文,混合体(图片+文字)  
  63.   
  64.         // 将附件和正文设置到这个邮件体中  
  65.         msgMultipart.addBodyPart(attch1);  
  66.         msgMultipart.addBodyPart(attch2);  
  67.         msgMultipart.addBodyPart(content);  
  68.           
  69.   
  70.         // 设置第一个附件  
  71.         DataSource ds1 = new FileDataSource("F:/ACCP5.0/文件/ssh配置.txt");// 指定附件的数据源  
  72.         DataHandler dh1 = new DataHandler(ds1);// 附件的信息  
  73.         attch1.setDataHandler(dh1);// 指定附件  
  74.         attch1.setFileName("ssh.txt");  
  75.   
  76.         // 设置第二个附件  
  77.         DataSource ds2 = new FileDataSource("resource/48.jpg");// 指定附件的数据源  
  78.         DataHandler dh2 = new DataHandler(ds2);// 附件的信息  
  79.         attch2.setDataHandler(dh2);// 指定附件  
  80.         attch2.setFileName("48.jpg");  
  81.   
  82.         //设置邮件的正文  
  83.         MimeMultipart bodyMultipart = new MimeMultipart("related");//依赖关系  
  84.         content.setContent(bodyMultipart);//指定正文  
  85.         MimeBodyPart htmlPart = new MimeBodyPart();  
  86.         MimeBodyPart gifPart = new MimeBodyPart();  
  87.         bodyMultipart.addBodyPart(htmlPart);  
  88.         bodyMultipart.addBodyPart(gifPart);  
  89.           
  90.           
  91.         DataSource gifds = new FileDataSource("resource/48.jpg");//正文的图片  
  92.         DataHandler gifdh = new DataHandler(gifds);  
  93.         gifPart.setHeader("Content-Location""http://mimg.126.net/logo/126logo.gif");  
  94.         gifPart.setDataHandler(gifdh);//设置正文的图片  
  95.           
  96.         htmlPart.setContent("我只是来打酱油的,这是我的形象照!<img src="/" mce_src="/""http://mimg.126.net/logo/126logo.gif/">", "text/html;charset=gbk");//设置正文文字  
  97.           
  98.         msg.saveChanges();//保存邮件  
  99.           
  100.         //将邮件保存成文件  
  101.         OutputStream ops = new FileOutputStream("C:/Users/Administrator/Desktop/test.eml");  
  102.         msg.writeTo(ops);  
  103.         ops.close();  
  104.           
  105.         Transport.send(msg);  
  106.     }  
  107.   
  108. }  


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 InetAddress.getLocalHost().getHostName() . Should not normally need to be set if your JDK and your name service are configured properly.
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 "LOGIN PLAIN DIGEST-MD5" , which includes all the authentication mechanisms supported by the current implementation.
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 setSubmitter method of SMTPMessage . Mail clients typically do not use this.
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 anSMTPAddressSucceededException for each address that is successful. Note also that this will cause aSendFailedException to be thrown from the sendMessagemethod of SMTPTransport even if all addresses were correct and the message was sent successfully.
mail.smtp.socketFactory
SocketFactory
If set to a class that implements thejavax.net.SocketFactory interface, this class will be used to create SMTP sockets. Note that this is an instance of a class, not a name, and must be set using the put method, not the setProperty method.
mail.smtp.socketFactory.class
String
If set, specifies the name of a class that implements thejavax.net.SocketFactory interface. This class will be used to create SMTP sockets.
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 java.net.Socket class. Defaults to true.
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 thejavax.net.ssl.SSLSocketFactory class, this class will be used to create SMTP SSL sockets. Note that this is an instance of a class, not a name, and must be set using theput method, not the setProperty method.
mail.smtp.ssl.socketFactory.class
String
If set, specifies the name of a class that extends thejavax.net.ssl.SSLSocketFactory class. This class will be used to create SMTP SSL sockets.
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 thejavax.net.ssl.SSLSocket.setEnabledProtocols method.
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 thejavax.net.ssl.SSLSocket.setEnabledCipherSuitesmethod.
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 SMTPTransportmethod supportsExtension to verify that the server supports the desired service extension. See RFC 1869 and other RFCs that define specific extensions.
mail.smtp.starttls.enable
boolean
If true, enables the use of the STARTTLS command (if supported by the server) to switch the connection to a TLS-protected connection before issuing any login commands. Note that an appropriate trust store must configured so that the client will trust the server's certificate. Defaults to false.
mail.smtp.starttls.required
boolean
If true, requires the use of the STARTTLS command. If the server doesn't support the STARTTLS command, or the command fails, the connect method will fail. Defaults to false.
mail.smtp.userset
boolean
If set to true, use the RSET command instead of the NOOP command in the isConnected method. In some cases sendmail will respond slowly after many NOOP commands; use of RSET avoids this sendmail issue. Defaults to false.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值