1.需要的maven依赖:
<dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.5.5</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> <version>2.5.6.SEC03</version> </dependency>
2.代码:
public class TestMain { @Test public void testMail(){ JavaMailSenderImpl theMail = new JavaMailSenderImpl (); theMail.setDefaultEncoding("UTF-8"); theMail.setUsername("*******@**.com");//发送邮箱 theMail.setPassword("*******");//开启smtp服务的密码串 theMail.setHost("smtp.163.com"); theMail.setPort(25);//常规邮箱有两种,不加密的走25号端口,加密的走465端口 Properties javaMailProperties=new Properties(); javaMailProperties.put("mail.smtp.auth", "true"); javaMailProperties.put("mail.smtp.timeout", 0); theMail.setJavaMailProperties(javaMailProperties); MimeMessage mailMessage = theMail.createMimeMessage(); MimeMessageHelper messageHelper; try { messageHelper = new MimeMessageHelper(mailMessage, true); messageHelper.setFrom(theMail.getUsername()); messageHelper.setTo("*******@**.com");//收件箱 messageHelper.setSubject("邮件测试");//主题 messageHelper.setText("< a href= 'www.baidu.com'>进入百度</ a>",true);//邮件内容 theMail.send(mailMessage); } catch (Exception e) { e.printStackTrace(); } System.out.println("邮件发送成功..."); } }