Android的 - 使用JavaMail和OAuth2发送电子邮件 [英] Android - Send Email using JavaMail and OAuth2
问题描述
我正在开发一个基本的电子邮件发送程序,发送电子邮件只到Gmail。过了一段时间我想通了OAuth2的孔方案,谷歌现在需要使用从 GoogleAuthUtil $ c中的
为gettoken()
方法验证$ C> API
I'm developing a basic email sender app that sends emails only to Gmail. After some time i figured out the hole scheme of the OAuth2 that Google now requires for authentication using the getToken()
method from the GoogleAuthUtil
API.
我在网上搜索了JavaMail的code使用,我从API检索令牌发送电子邮件,我发现我使用现在下面的code:
I've searched on the web for the JavaMail code to send the email using the token that i retrieve from the API and i found the following code that i'm using now:
package com.provider;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Provider;
import java.security.Security;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.URLName;
import javax.mail.Message;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.util.ByteArrayDataSource;
import android.util.Log;
import com.sun.mail.smtp.SMTPTransport;
import com.sun.mail.util.BASE64EncoderStream;
public class GMailOauthSender {
private Session session;
private String mailhost = "smtp.gmail.com";
private int port = 587;
private String user;
private String password;
public SMTPTransport connectToSmtp(String host, int port, String userEmail,
String oauthToken, boolean debug) throws Exception {
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.starttls.required", "true");
props.put("mail.smtp.sasl.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.imap.auth.login.disable", "true");
props.put("mail.imap.auth.plain.disable", "true");
session = Session.getInstance(props);
session.setDebug(debug);
final URLName unusedUrlName = null;
SMTPTransport transport = new SMTPTransport(session, unusedUrlName);
// If the password is non-null, SMTP tries to do AUTH LOGIN.
final String emptyPassword = null;
transport.connect(host, port, userEmail, emptyPassword);
byte[] response = String.format("user=%s\1auth=Bearer %s\1\1", userEmail,
oauthToken).getBytes();
response = BASE64EncoderStream.encode(response);
transport.issueCommand("AUTH XOAUTH2 " + new String(response),
235);
return transport;
}
public synchronized void sendMail(String subject, String body, String user,
String oauthToken, String recipients) {
try {
SMTPTransport smtpTransport = connectToSmtp("smtp.gmail.com",
587,
user,
oauthToken,
true);
MimeMessage message = new MimeMessage(session);
DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
message.setSender(new InternetAddress(user));
message.setSubject(subject);
message.setDataHandler(handler);
if (recipients.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
smtpTransport.sendMessage(message, message.getAllRecipients());
} catch (Exception e) {
//Log.d("test", e.getMessage());
}
}
不幸的是,code根本不起作用。我已经贴本了三个多星期,没有什么至今。有什么建议?
Unfortunately, the code simply does not work. I've been sticked with this for more than three weeks and nothing so far. Any suggestions?
推荐答案
这是真正的痛苦,当我这样做第一次,并使其work..Follow这些步骤
It was real pain when I did this first time and to make it work..Follow these steps
首先,您需要设置OAuth2在开发者控制台中您的应用程序,去这个链接详细信息
First you need to setup OAuth2 for your app in developer console, go to this link for details
现在,您需要添加这4个文件,这些将有助于发送邮件的背景。当用户打开应用程序的用户将显示的同意屏(code文件AUthActivity.java),并且必须允许应用程序来使用Gmail,这是一次活动,以后不是必需的。在这样做时用户请求从谷歌服务器的令牌,将被保存在preferences,使用户不会被再次问(验证preferences.java)。经过用户同意它,你可以通过发送邮件:
Now you need to add these 4 files, these will help to send mail in background. When users open the app users will be shown a consent screen(Code in file AUthActivity.java) and will have to allow the app to use gmail, this is one time activity and not required later. When doing this user is requesting a token from google servers and will be saved in preferences so that users is not asked again(AuthPreferences.java). After user approves it you can send mail using:
GMailSender gMailSender = new GMailSender();
gMailSender.sendMail("hi", "hi", authPreferences.getUser(), authPreferences.getToken(), "somemailid@gmail.com");
链接在GitHub上的文件: https://gist.github.com/ranjithnair02/1c6dab7dec51971abfec一>
您还需要将以下jar文件添加到您的项目:
You also need to add the below jar files to your project:
HTTP://javamail-android.google$c$c。 COM /文件/ mail.jar中
HTTP://javamail-android.google$c$c。 COM /文件/的activation.jar
HTTP://javamail-android.google$c$c。 COM /文件/ additionnal.jar
您还需要添加以下在AndroidManifest.xml中
You also need to add the following in Androidmanifest.xml
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
这篇关于Android的 - 使用JavaMail和OAuth2发送电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!