使用java mail(jmail)通过gmail的stmp发送邮件:SSL方式
http://stackoverflow.com/questions/1990454/using-javamail-to-connect-to-gmail-smtp-server-ignores-specified-port-and-tries
1 2 3 4 5 |
Java代码 Transport transport = session.getTransport("smtps"); transport.connect (smtp_host, smtp_port, smtp_username, smtp_password); transport.sendMessage(msg, msg.getAllRecipients()); transport.close(); |
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 |
Java代码 public static boolean sendGmailEmail() { Properties props = new Properties(); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.auth", "true"); props.put("mail.debug", "false"); props.put("mail.smtp.port", Integer.parseInt("465")); props.put("mail.smtp.socketFactory.port", Integer.parseInt("465")); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); // Session session = Session.getInstance(props); Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("formEmail@gmail.com", "77185201314"); } }); javax.mail.Message msg = new MimeMessage(session); try { msg.setFrom(new InternetAddress("formEmail@gmail.com")); msg.setSubject("Subject"); Multipart mp = new MimeMultipart(); MimeBodyPart mbp = new MimeBodyPart(); mbp.setContent("This is a message.", "text/html;charset=UTF-8"); mp.addBodyPart(mbp); msg.setContent(mp); Transport transport = session.getTransport(); transport.connect("smtp.gmail.com", Integer.parseInt("465"), "formEmail@gmail.com", "123456"); transport.sendMessage(msg, new Address[] { new InternetAddress("toEmail@qq.com") }); transport.close(); } catch (Exception e) { e.printStackTrace(); return false; } return true; } |