【问题标题】:Java Send Email via gmailJava 通过 gmail 发送电子邮件
【发布时间】:2016-09-26 12:30:29
【问题描述】:

以下代码应该通过 gmail 发送电子邮件,但它给出了以下错误:

在我的 gmail 帐户上,我收到一条消息,指出登录被阻止,我应该使用像 gmail 这样的安全应用来访问我的帐户。源码如下图:

public void doSendMail(){
    username = txtFrom.getText();
    password= new String(txtPassword.getPassword());
    to = txtTo.getText();
    subject = txtSubject.getText();
    email_body = jTextArea1.getText();

    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "587");
    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", "587");

    Session session = Session.getDefaultInstance(props,
            new javax.mail.Authenticator(){
                @Override
                protected PasswordAuthentication getPasswordAuthentication(){
                    return new PasswordAuthentication(username, password);
                }
    }
    );
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(username));
        message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));
        message.setSubject(subject);
        message.setText(email_body);
        Transport.send(message);

        JOptionPane.showMessageDialog(this, "Message Sent!","Sent",JOptionPane.INFORMATION_MESSAGE);

    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, e.toString());
    }
}

我可以对代码做些什么以使其通过 gmail 发送邮件?

【问题讨论】:

  • 能否贴出可以复制的错误信息文本?
  • 我将 try...catch 块捕获的错误设置为显示在消息对话框中。我相信错误显示在我发布的消息对话框中

标签: java gmail send


【解决方案1】:

您的源代码非常适合通过 gmail 发送电子邮件。可能您必须允许您的帐户通过https://www.google.com/settings/security/lesssecureapps 进行不太安全的访问

这是您的代码。我做了很少的修改以作为独立程序运行。它需要两个罐子:1)mail-1.4.7.jar 和 2)activation-1.1.1.jar

import java.util.Properties;
import java.util.Scanner;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.swing.JOptionPane;

/**
 *  Following jar are required:
 *  1) mail-1.4.7.jar from http://central.maven.org/maven2/javax/mail/mail/1.4.7/mail-1.4.7.jar
 *  2) activation-1.1.1.jar from http://central.maven.org/maven2/javax/activation/activation/1.1.1/activation-1.1.1.jar
 *
 */
public class Test {

    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.print("gmail username: ");
        String username = sc.next();
        System.out.print("gmail password: ");
        String password = sc.next();
        System.out.print("destination email address: ");
        String to = sc.next();
        System.out.print("subject: ");
        String subject = sc.next();
        System.out.print("email body: ");
        String email_body = sc.next();
        Test test = new Test();
        test.doSendMail(username, password, to, subject, email_body);
        sc.close();

    }
    // sends mail
    public void doSendMail(final String username, final String password, String to, String subject, String email_body) {

        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.socketFactory.port", "587");
        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", "587");

        Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(username));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            message.setSubject(subject);
            message.setText(email_body);
            Transport.send(message);
            System.out.println("message sent");
            JOptionPane.showMessageDialog(null, "Message Sent!", "Sent", JOptionPane.INFORMATION_MESSAGE);
        } catch (Exception e) {
            System.out.println(e);
            JOptionPane.showMessageDialog(null, e.toString());
        }
    }
}

【讨论】:

  • 我倾向于认为这可能是问题所在,但是activation-1.1.1.jar 有什么作用呢?
  • 我使用 javax.swing.mail.jar 版本 1.5.5
  • 在打开不太安全的应用程序后工作。谢谢@Sanjeev Saha
  • 无效:javax.mail.MessagingException:无法连接到 SMTP 主机:smtp.xyz.com,端口:587;嵌套异常是:java.net.ConnectException:连接超时:连接
  • @ShamimAhmad 你的堆栈跟踪显示你正在使用mail.smtp.host=smtp.xyz.com,这是错误的!!!你应该使用mail.smtp.host=smtp.gmail.com。请将您的值与本程序中给出的值进行比较。它应该可以工作。
【解决方案2】:

对我来说正在使用这个属性:

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.port", "465");

希望对你有帮助。

【讨论】:

【解决方案3】:

试试这个:

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;

public class SendMailSSL {

    public static void main(String[] args) {

        String to = "krishna14581@gmail.com";//change accordingly  

        //Get the session object  
        Properties props = new Properties();
        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.port", "465");

        Session session = Session.getDefaultInstance(props,
                new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("yourgmailid@gmail.com", "password");//change accordingly  
            }
        });

        //compose message  
        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress("yourgmailid@gmail.com"));//change accordingly  
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject("Hello");
            message.setText("Testing.......");

            //send message  
            Transport.send(message);

            System.out.println("message sent successfully");

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

    }
}

【讨论】:

  • 收到了相同的消息,但当您将主机更改为“smtp.mail.yahoo.com”时,它对 yahoo 有效。
  • 尝试“smtp-relay.gmail.com”作为主机。
  • 我在 google 上打开了安全性较低的应用程序的访问权限,它工作得很好。无需修改代码
【解决方案4】:

只需转到:https://myaccount.google.com/security 转到页面底部并启用:允许不太安全的应用程序

【讨论】:

    猜你喜欢
    • 2012-01-07
    • 2023-03-19
    • 2013-02-03
    • 2011-06-01
    • 2018-03-21
    • 1970-01-01
    相关资源
    最近更新 更多