Java通过Gmail发送电子邮件

时间:2016-05-28 06:06:46

标签: java gmail send

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

enter image description here

在我的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发送邮件?

4 个答案:

答案 0 :(得分:5)

您的源代码非常适合通过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());
        }
    }
}

答案 1 :(得分:0)

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

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");

希望它有所帮助。

答案 2 :(得分:0)

试试这个:

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);
        }

    }
}

答案 3 :(得分:0)

只需转到:https://myaccount.google.com/security     转到页面底部并启用:允许安全性较低的应用