刚开始用的邮箱账号是在网易163刚注册的号码,结果总是失败,以为是自己的代码哪里有问题,可是和别人的代码对照检查了一遍,也没找到问题,十分纠结,突然想我使用的smtp发送的邮件,我查看了网易邮箱的设置有一个POP3/SMTP/IMAP选项:
点击后:
看到这个之后顿时感觉无语。。默认竟然是关闭STMP服务!!!!
所以换了一个公司的邮箱,腾讯的邮箱发送没问题,但是接收可能存在问题,但应该不是代码的问题。
package cn.Lionel.javamail; import java.io.File; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message.RecipientType; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; 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; import org.junit.Test; public class Demo1 { /** * 不带附件的普通邮件 * * @throws Exception */ @Test public void test1() throws Exception { Properties props = new Properties() ; props.setProperty("mail.host", "smtp.qq.com") ; props.setProperty("mail.smtp.auth", "true") ; Authenticator authenticator = new Authenticator(){ @Override protected PasswordAuthentication getPasswordAuthentication() { //lzy_lionel:对应你自己的用户名,后面没有@.xxx ; password 对应你自己的邮箱密码 return new PasswordAuthentication("from", "password") ; } }; Session session = Session.getInstance(props, authenticator) ; MimeMessage msg = new MimeMessage(session) ; msg.setFrom(new InternetAddress("[email protected]")); //发送给: msg.setRecipients(RecipientType.TO,"[email protected]") ; //抄送给: msg.setRecipients(RecipientType.CC,"[email protected]") ; //暗送给: msg.setRecipients(RecipientType.BCC,"[email protected]") ; //设置主题: msg.setSubject("这是一封测试邮件!"); //设置内容: msg.setContent("你好,收到请回复!", "text/html;charset=utf-8") ; Transport.send(msg); } /** * 发送带附件的邮件! * @throws Exception */ @Test public void test2() throws Exception { Properties props = new Properties() ; props.setProperty("mail.host", "smtp.qq.com") ; props.setProperty("mail.smtp.auth", "true") ; Authenticator authenticator = new Authenticator(){ @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("from", "password") ; } }; Session session = Session.getInstance(props, authenticator) ; MimeMessage msg = new MimeMessage(session) ; msg.setFrom(new InternetAddress("[email protected]")); msg.setRecipients(RecipientType.TO,"[email protected]") ; msg.setSubject("这是一封测试邮件!"); MimeMultipart list = new MimeMultipart() ; MimeBodyPart part1 = new MimeBodyPart() ; part1.setContent("你好,收到请回复!", "text/html;charset=utf-8") ; list.addBodyPart(part1); MimeBodyPart part2 = new MimeBodyPart(); //下面的路径应该对应着是你自己文件所在的路径 part2.attachFile(new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\1.jpg")) ; //MimeUtility.encodeText()防止文字乱码 part2.setFileName(MimeUtility.encodeText("美女.jpg")); list.addBodyPart(part2); msg.setContent(list); Transport.send(msg); } }
大功告成!
附上一个对javaMail的入门地址:http://blog.csdn.net/zapldy/article/details/3971579
附上所需javaMail的jar资源: http://download.csdn.net/detail/lionel_d/9309583
和JavaMail的文档资源:http://download.csdn.net/detail/lionel_d/9309509
水平有限,代码若有问题还望指出!