如何配置Java应用程序使用OAUTH2向Gmail服务发送电子邮件?

huangapple 未分类评论51阅读模式
英文:

How to configure Java Application to send Email with Gmail service using OAUTH2?

问题

我已配置了我的Java应用程序使用OAUTH2,但出现了错误。请问有人能提供解决方案吗?

以下是代码部分:

public static void main(String args[]) {
    String TOKEN_URL = "https://www.googleapis.com/oauth2/v4/token";
    String oauthClientId = "558561226799-6nvqdl1kabh863g1a1184t3t7fcvu82e.apps.googleusercontent.com";
    String oauthSecret = "UAPodrF7mIAverk_-A8wlWyL";
    String refreshToken = "1//0gyh0jPCTq5GSCgYIARAAGBASNwF-L9IrGNizcIn4l4tGhlORji0X6zqFsV4rsB-niM1lNtJa9nVedsTWWPBt9Uuj8pOPcHNrpfc";
    String accessToken = "ya29.a0Ae4lvC2p0j2MK6Wv5CcXvcB9VwJmukivtY7M6y6ZBntBdIls5XAXe4TCjt9zr5VuWolB0CdRJjL6UBIz5mqj63KvNxjAYU0DeNsZGbWrz7daP624ruvM-DYsvHSUx1jrUcudiUDF2YhQc3lHH8WXrAhanWIBakI170w";
    long tokenExpires = 1458168133864L;
    String username = "bittu9601164625@gmail.com";

    if (System.currentTimeMillis() > tokenExpires) {
        try {
            String request = "client_id=" + URLEncoder.encode(oauthClientId, "UTF-8")
                    + "&client_secret=" + URLEncoder.encode(oauthSecret, "UTF-8")
                    + "&refresh_token=" + URLEncoder.encode(refreshToken, "UTF-8")
                    + "&grant_type=refresh_token";
            HttpURLConnection conn = (HttpURLConnection) new URL(TOKEN_URL).openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            PrintWriter out = new PrintWriter(conn.getOutputStream());
            out.print(request);
            out.flush();
            out.close();
            conn.connect();
            try {
                HashMap<String, Object> result;
                result = new ObjectMapper().readValue(conn.getInputStream(), new TypeReference<HashMap<String, Object>>() {
                });
                accessToken = (String) result.get("access_token");
                tokenExpires = System.currentTimeMillis() + (((Number) result.get("expires_in")).intValue() * 1000);
            } catch (IOException e) {
                // Error handling code here
            }
        } catch (Exception e) {
            // Error handling code here
        }
    }

    String mailUsername = "bittu9601164625@gmail.com";

    Properties props = new Properties();
    props.put("mail.smtp.ssl.enable", "true");
    props.put("mail.smtp.auth.mechanisms", "XOAUTH2");

    try {
        // Sending email code here
    } catch (AddressException e) {
        // Error handling code here
    } catch (NoSuchProviderException e) {
        // Error handling code here
    } catch (MessagingException e) {
        // Error handling code here
    }
}

下面是我得到的错误信息,我没有将主机名设置为localhost或任何端口号,connect方法是否不起作用?

javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;
nested exception is:
java.net.ConnectException: Connection refused (Connection refused)
...
Caused by: java.net.ConnectException: Connection refused (Connection refused)
...
Process finished with exit code 0

请有人告诉我我做错了什么。如果有其他解决方案,将不胜感激。

英文:

I have configured my Java Application using OAUTH2 but it is giving me error. Can someone please suggest me a solution ?'

Below is the code:

public static void main (String args[]){

	String TOKEN_URL = &quot;https://www.googleapis.com/oauth2/v4/token&quot;;
	String oauthClientId = &quot;558561226799-6nvqdl1kabh863g1a1184t3t7fcvu82e.apps.googleusercontent.com&quot;;
	String oauthSecret = &quot;UAPodrF7mIAverk_-A8wlWyL&quot;;
	String refreshToken = &quot;1//0gyh0jPCTq5GSCgYIARAAGBASNwF-L9IrGNizcIn4l4tGhlORji0X6zqFsV4rsB-niM1lNtJa9nVedsTWWPBt9Uuj8pOPcHNrpfc&quot;;
	String accessToken = &quot;ya29.a0Ae4lvC2p0j2MK6Wv5CcXvcB9VwJmukivtY7M6y6ZBntBdIls5XAXe4TCjt9zr5VuWolB0CdRJjL6UBIz5mqj63KvNxjAYU0DeNsZGbWrz7daP624ruvM-DYsvHSUx1jrUcudiUDF2YhQc3lHH8WXrAhanWIBakI170w&quot;;
	long tokenExpires = 1458168133864L;
	String username=&quot;bittu9601164625@gmail.com&quot;;

	if (System.currentTimeMillis() &gt; tokenExpires) {
		try {
			String request = &quot;client_id=&quot; + URLEncoder.encode(oauthClientId, &quot;UTF-8&quot;)
					+ &quot;&amp;client_secret=&quot; + URLEncoder.encode(oauthSecret, &quot;UTF-8&quot;)
					+ &quot;&amp;refresh_token=&quot; + URLEncoder.encode(refreshToken, &quot;UTF-8&quot;)
					+ &quot;&amp;grant_type=refresh_token&quot;;
			HttpURLConnection conn = (HttpURLConnection) new URL(TOKEN_URL).openConnection();
			conn.setDoOutput(true);
			conn.setRequestMethod(&quot;POST&quot;);
			PrintWriter out = new PrintWriter(conn.getOutputStream());
			out.print(request); // note: println causes error
			out.flush();
			out.close();
			conn.connect();
			try {
				HashMap&lt;String, Object&gt; result;
				result = new ObjectMapper().readValue(conn.getInputStream(), new TypeReference&lt;HashMap&lt;String, Object&gt;&gt;() {
				});
				accessToken = (String) result.get(&quot;access_token&quot;);
				tokenExpires = System.currentTimeMillis() + (((Number) result.get(&quot;expires_in&quot;)).intValue() * 1000);
			} catch (IOException e) {
				String line;
				BufferedReader in = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
				while ((line = in.readLine()) != null) {
					System.out.println(line);
				}
				System.out.flush();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	String mailUsername = &quot;bittu9601164625@gmail.com&quot;;

	Properties props = new Properties();
	props.put(&quot;mail.smtp.ssl.enable&quot;, &quot;true&quot;); // required for Gmail
	props.put(&quot;mail.smtp.auth.mechanisms&quot;, &quot;XOAUTH2&quot;);

	try {
		Session session = Session.getInstance(props);

		Message msg = new MimeMessage(session);
		msg.setFrom(new InternetAddress(mailUsername));
		msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mailUsername));

		msg.setSubject(&quot;JavaMail OAuth2 test&quot;);
		msg.setSentDate(new Date());
		msg.setText(&quot;Hello, world with OAuth2!\n&quot;);
		msg.saveChanges();

		Transport transport = session.getTransport(&quot;smtp&quot;);
		transport.connect(&quot;smtp.gmail.com&quot;, username, accessToken);
		transport.send(msg, msg.getAllRecipients());
	} catch (AddressException e) {
		e.printStackTrace();
	} catch (NoSuchProviderException e) {
		e.printStackTrace();
	} catch (MessagingException e) {
		e.printStackTrace();
	}
}

And below is the error that I am getting, I have not mentioned host as localhost or any port number, is the connect method not working ? :

javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;
  nested exception is:
	java.net.ConnectException: Connection refused (Connection refused)
	at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1282)
	at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:370)
	at javax.mail.Service.connect(Service.java:275)
	at javax.mail.Service.connect(Service.java:156)
	at javax.mail.Service.connect(Service.java:105)
	at javax.mail.Transport.send0(Transport.java:168)
	at javax.mail.Transport.send(Transport.java:120)
	at com.rapidbox.wmscore.service.impl.VendorServiceImpl.main(VendorServiceImpl.java:158)
Caused by: java.net.ConnectException: Connection refused (Connection refused)
	at java.net.PlainSocketImpl.socketConnect(Native Method)
	at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
	at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
	at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
	at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
	at java.net.Socket.connect(Socket.java:607)
	at java.net.Socket.connect(Socket.java:556)
	at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:232)
	at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189)
	at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1250)
	... 7 more

Process finished with exit code 0

Please someone tell me what I am doing wrong. Also if there is ant alternative solution then it would be appreciated.

答案1

得分: 0

似乎您的防火墙或防病毒软件正在阻止您进行连接。
请参阅JavaMail连接调试提示

英文:

Looks like you have a firewall or antivirus preventing you from connecting.
See the JavaMail connection debugging tips.

huangapple
  • 本文由 发表于 2020年4月10日 19:13:17
  • 转载请务必保留本文链接:https://java.coder-hub.com/61139106.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定