小编Dav*_*vid的帖子

Java通过Gmail发送电子邮件

以下代码应该通过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());
    }
}
Run Code Online (Sandbox Code Playgroud)

我可以对代码做什么让它通过gmail发送邮件?

java gmail send

4
推荐指数
1
解决办法
3617
查看次数

标签 统计

gmail ×1

java ×1

send ×1