代码之家  ›  专栏  ›  技术社区  ›  dancavallaro

将JavaMail与TLS结合使用

  •  46
  • dancavallaro  · 技术社区  · 17 年前

    5 回复  |  直到 17 年前
        1
  •  74
  •   George Brighton    12 年前

    Properties props = new Properties();
    props.put("mail.smtp.starttls.enable","true");
    props.put("mail.smtp.auth", "true");  // If you need to authenticate
    // Use the following if you need SSL
    props.put("mail.smtp.socketFactory.port", d_port);
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");
    

    然后,您可以将其传递给JavaMail会话或任何其他会话实例化器等 Session.getDefaultInstance(props) .

        2
  •  27
  •   jasonsmith jasonsmith    17 年前

    好帖子,这条线

    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    

    如果SMTP服务器使用 TLS上的明文认证 ,它不应该出现,因为Java Mail会抱怨初始连接是纯文本的。

        3
  •  9
  •   Brent Matzelle    15 年前

    上面示例中的设置对我使用的服务器不起作用( authsmtp.com ).我不断地发现这个错误:

    javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
    

    我删除了mail.smtp.socketFactory设置,一切正常。最终设置如下(未使用SMTP身份验证,我在其他地方设置了端口):

    java.util.Properties props = new java.util.Properties();
    props.put("mail.smtp.starttls.enable", "true");
    
        4
  •  7
  •   james.garriss Pavel    13 年前

    import java.util.*;
    import javax.activation.CommandMap;
    import javax.activation.MailcapCommandMap;
    import javax.mail.*;
    import javax.mail.Provider;
    import javax.mail.internet.*;
    
    public class Main {
    
        public static void main(String[] args) {
                final String username="your@gmail.com";
                final String password="password";
                Properties prop=new Properties();
                prop.put("mail.smtp.auth", "true");
                prop.put("mail.smtp.host", "smtp.gmail.com");
                prop.put("mail.smtp.port", "587");
                prop.put("mail.smtp.starttls.enable", "true");
    
                Session session = Session.getDefaultInstance(prop,
              new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
              }
            });
              try {
                     String body="Dear Renish Khunt Welcome";
                     String htmlBody = "<strong>This is an HTML Message</strong>";
                     String textBody = "This is a Text Message.";
             Message message = new MimeMessage(session);
             message.setFrom(new InternetAddress("your@gmail.com"));
                     message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("receiver@gmail.com"));
            message.setSubject("Testing Subject");
            MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
            mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
            mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
            mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
            mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
            mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
            CommandMap.setDefaultCommandMap(mc);
                message.setText(htmlBody);
                            message.setContent(textBody, "text/html");
                Transport.send(message);
    
                System.out.println("Done");
    
            } catch (MessagingException e) {
                e.printStackTrace();
            }
    
        }
    
    }
    
        5
  •  2
  •   Benny Bottema    8 年前

    具有 Simple Java Mail 5.0.0 (simplejavamail.org)这非常简单,库将为您处理所有会话属性。

    Email email = EmailBuilder.startingBlank()
            .from("lollypop", "lol.pop@somemail.com")
            .to("C.Cane", "candycane@candyshop.org")
            .withSubject("hey")
            .withPlainText("We should meet up!")
            .withHTMLText("<b>We should meet up!</b>")
            .buildEmail();
    
    MailerBuilder.withSMTPServer("smtp.gmail.com", 25, "user", "pass", SMTP_TLS)
            .buildMailer()
            .sendMail(email);
    
    MailerBuilder.withSMTPServer("smtp.gmail.com", 587, "user", "pass", SMTP_TLS)
            .buildMailer()
            .sendMail(email);
    
    MailerBuilder.withSMTPServer("smtp.gmail.com", 465, "user", "pass", SMTP_SSL)
            .buildMailer()
            .sendMail(email);
    

    application specific password 从你的谷歌帐户。

        6
  •  1
  •   Evgeniy Noskov    5 年前

    作为一个小提示,当我在上面的示例中根据javamail的示例将smtp更改为smtps时,它才开始对我起作用(参见smtpsend.java, https://github.com/javaee/javamail/releases/download/JAVAMAIL-1_6_2/javamail-samples.zip

    我的结果代码如下所示:

    Properties props=new Properties();
    props.put("mail.smtps.starttls.enable","true");
    // Use the following if you need SSL
    props.put("mail.smtps.socketFactory.port", port);
    props.put("mail.smtps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtps.socketFactory.fallback", "false");
    props.put("mail.smtps.host", serverList.get(randNum));
    Session session = Session.getDefaultInstance(props);
    
    smtpConnectionPool = new SmtpConnectionPool(
        SmtpConnectionFactories.newSmtpFactory(session));
        
    final ClosableSmtpConnection transport = smtpConnectionPool.borrowObject();
    ...
    transport.sendMessage(message, message.getAllRecipients());
    
        7
  •  1
  •   Kristof Neirynck    5 年前

    faq ,但得到了 javadoc .

    如果你忘了 props.put("mail.smtp.starttls.enable","true") 你得到 com.sun.mail.smtp.SMTPSendFailedException: 451 5.7.3 STARTTLS is required to send mail .

    如果你忘了 props.put("mail.smtp.ssl.protocols", "TLSv1.2"); javax.mail.MessagingException: Could not convert socket to TLS; 和 No appropriate protocol (protocol is disabled or cipher suites are inappropriate)

    以下是使其工作所需的最低代码:

    import java.util.Properties;
    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;
    
    public class SendEmail {
        public static void main(String[] args) {
            Properties props = new Properties();
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.starttls.enable","true");
            // smtp.gmail.com supports TLSv1.2 and TLSv1.3
            // smtp.office365.com supports only TLSv1.2
            props.put("mail.smtp.ssl.protocols", "TLSv1.2");
            props.put("mail.smtp.host", "smtp.office365.com");
            props.put("mail.smtp.port", "587");
            
            Session session = Session.getInstance(props, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("test@example.com", "******");
                }
            });
            
            try {
                Message message = new MimeMessage(session);
                message.setFrom(new InternetAddress("sender@example.com"));
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipient@example.com"));
                message.setSubject("You got mail");
                message.setText("This email was sent with JavaMail.");
                Transport.send(message);
                System.out.println("Email sent.");
            } catch (MessagingException e) {
                throw new RuntimeException(e);
            }
        }
    }