Java 发送邮件
本节作为对菜鸟教程-SendMail的补充。
开始需要下载相应的Jar
包,并添加到ClassPath
,发送邮箱选择的是自己的Gmail邮箱(推荐),接收邮箱是网易邮箱(任意),SMTP
协议选择的端口是Port:465
(推荐,一般会默认Port:25
,但是容易报MessagingException)。如果使用Gmail作为发送邮箱的话,会发现使用谷歌账户的密码依然会出AuthenticationFailedException
异常,因为google开启了两步验证功能,所以如果要使用javamail
发送邮件的话,需要一个应用专用密码(app password
),这样即使密码被盗取也无法登录到账号。这里是谷歌官方提供的方法- 应用专用密码。
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
|
import java.util.*; import javax.mail.*; import javax.mail.internet.*; import javax.activation.*;
public class SendEmail { public static void main(String [] args) { final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; String from = "YourGmail@gmail.com";
String to = "XXX@163.com";
String host = "smtp.gmail.com";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", "smtp.gmail.com"); properties.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY); properties.setProperty("mail.smtp.socketFactory.fallback", "false"); properties.setProperty("mail.smtp.port", "465"); properties.setProperty("mail.smtp.socketFactory.port", "465"); properties.put("mail.smtp.auth", "true"); properties.put("mail.debug", "true"); properties.put("mail.store.protocol", "pop3"); properties.put("mail.transport.protocol", "smtp"); final String username = from; final String password = "YourAppPassword"; Session session = Session.getDefaultInstance(properties, new Authenticator(){ @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); }});
try{ MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to,false));
message.setSubject("This is the Subject Line!");
message.setText("This is actual message");
Transport.send(message); System.out.println("Sent message successfully...."); }catch (MessagingException mex) { mex.printStackTrace(); } } }
|