首先下载javax.mail.jar包,[点击下载]
(https://github.com/javaee/javamail/releases)
注意:
不需要下载activation.jar,JDK1.5以后这个jar包已经集成到JDK了,亲测有效。
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
| package pers.husen.sendemail;
import java.io.UnsupportedEncodingException; import java.security.GeneralSecurityException; import java.util.Properties;
import javax.mail.Address; 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.InternetAddress; import javax.mail.internet.MimeMessage; import com.sun.mail.util.MailSSLSocketFactory;
public class SendEmail { public static void main(String[] args) { try { Properties properties = new Properties(); MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.ssl.enable", "true"); properties.put("mail.smtp.ssl.socketFactory", sf); properties.setProperty("mail.host", "smtp.qq.com"); properties.setProperty("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(properties, new Authenticator() { @Override public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("husen@hemingsheng.cn", "此处填密码(QQ邮箱填授权码)"); } }); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress("husen@hemingsheng.cn", "何明胜", "UTF-8")); message.addRecipient(Message.RecipientType.TO, new InternetAddress("1123767053@qq.com")); message.setSubject("来自测试的邮件标题!"); message.setContent("邮件内容123", "text/html;charset=UTF-8");
Transport transport = session.getTransport(); transport.connect(); transport.sendMessage(message, new Address[] { new InternetAddress("对方的邮箱@qq.com") }); transport.close(); System.out.println("Sent message successfully....from console"); } catch (MessagingException | UnsupportedEncodingException | GeneralSecurityException mex) { mex.printStackTrace(); } } }
|
全文完。