Java连接gmail并发送文件

标签 java email gmail attachment

代码:

public static void sendMailAttachments(String mensaje, String cartera, String asunto, String file) throws AddressException, MessagingException, IOException{

    //Get user, pass, to
    getDatosCorreo();

    Properties props = new Properties();
    props.put("mail.smtp.port", "465");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.ssl.trust", "smtp.gmail.com");
    props.put("mail.smtp.starttls.enable", "true");

    Session session = Session.getDefaultInstance(props,
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(user,pass);
                }
            });
    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(user));

        message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(to.get(0)));

        message.setSubject("Email Subject - Asunto del correo electronico");

        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText("Email text Body - Texto o cuerpo del correo electronico");

        Multipart multipart = new MimeMultipart();
        multipart = addAttachment(multipart, file);

        //Setting email text message
        multipart.addBodyPart(messageBodyPart);

        //set the attachments to the email
        message.setContent(multipart);

        Transport.send(message);

        System.out.println("Correo enviado");

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }

}

异常(exception):

GRAVE: The RuntimeException could not be mapped to a response, re-throwing to the HTTP container java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 465, response: -1 at util.MAIL.sendMailAttachments(MAIL.java:128)

如何连接并发送文件?

此代码连接到 Gmail 并发送消息。

我需要添加一个文件才能发送。

getDatosCorreo();

// TODO Auto-generated method stub
// Step1
System.out.println("\n 1st ===> setup Mail Server Properties..");
mailServerProperties = System.getProperties();
mailServerProperties.put("mail.smtp.port", "587");
mailServerProperties.put("mail.smtp.auth", "true");
mailServerProperties.put("mail.smtp.ssl.trust", "smtp.gmail.com");
mailServerProperties.put("mail.smtp.starttls.enable", "true");
System.out.println("Mail Server Properties have been setup successfully..");

// Step2
System.out.println("\n\n 2nd ===> get Mail Session..");
getMailSession = Session.getDefaultInstance(mailServerProperties, null);
generateMailMessage = new MimeMessage(getMailSession);
for(int i = 0; i < to.size(); i++) {
    if(i == 0) {
        generateMailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to.get(i)));
    }else {
        generateMailMessage.addRecipient(Message.RecipientType.CC, new InternetAddress(to.get(i)));
    }
}
generateMailMessage.setSubject(asunto+cartera);
generateMailMessage.setContent(mensaje, "text/html");
System.out.println("Mail Session has been created successfully..");

// Step3
System.out.println("\n\n 3rd ===> Get Session and Send mail");
Transport transport = getMailSession.getTransport("smtp");

// Enter your correct gmail UserID and Password
// if you have 2FA enabled then provide App Specific Password
transport.connect("smtp.gmail.com", user, pass);
transport.sendMessage(generateMailMessage, generateMailMessage.getAllRecipients());
transport.close();
System.out.println("\n\n 4rd ===> Send email correctly");

最佳答案

当我使用带有 SSL 的电子邮件服务时,以下设置适用于我:

props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.port", "465");

我不知道您是否需要设置mail.smtp.ssl.trust属性。 This SO answer不需要它,我也不需要让它与我的特定 SSL 电子邮件服务一起工作。

关于Java连接gmail并发送文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49128971/

相关文章:

email - 带有 Gsuite 的 Meteor 电子邮件,未知协议(protocol)错误

java - 需要帮助来理解 spring 配置文件

java - 水平翻转 Sprite slick2d

java - 找不到 com.mongodb.ServerAddress 的类文件

node.js - 无法使用expressjs和nodejs发送电子邮件

ruby-on-rails - 使用 Rails 4 和 Devise 发送电子邮件时出错(连接被拒绝,端口 25)

ruby - 使用 ruby​​-gmail 读取 Gmail 邮件

Java - 获取数组中的元素位置

php - OpenSSL 已启用但无法找到包装器 "ssl"

authentication - 我可以在获取 chrome 身份 token 之前选择用户吗?