在java中使用Gmail API发送电子邮件
我想写一个Java程序,可以发送电子邮件到任何Gmail帐户。 我正在为此搜索API。到目前为止,我发现Gmail API很有用。我还在谷歌的开发者控制台上创建了一个应用程序。我在Gmail API中找不到任何Oauth授权和电子邮件发送的例子。有人可以参考任何资料或链接吗?试试JavaMail API 要使用它,您需要两个依赖项:javaee.jar和mail.jar在java中使用Gmail API发送电子邮件,java,email,gmail,Java,Email,Gmail,我想写一个Java程序,可以发送电子邮件到任何Gmail帐户。 我正在为此搜索API。到目前为止,我发现Gmail API很有用。我还在谷歌的开发者控制台上创建了一个应用程序。我在Gmail API中找不到任何Oauth授权和电子邮件发送的例子。有人可以参考任何资料或链接吗?试试JavaMail API 要使用它,您需要两个依赖项:javaee.jar和mail.jar Properties props = new Properties(); props.put("mail.smtp.h
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("username","password");
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from@no-spam.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to@no-spam.com"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler," +
"\n\n No spam to my email, please!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
我能够使用这种方法发送电子邮件(虽然我的界面是droid,但这可能会对您有所帮助): 我创建了一个单独的类,下面的代码取自gmail api示例。出于测试目的,我将这个类称为SendMail
/**
* Send an email from the user's mailbox to its recipient.
*
* @param service Authorized Gmail API instance.
* @param userId User's email address. The special value "me"
* can be used to indicate the authenticated user.
* @param email Email to be sent.
* @throws MessagingException
* @throws IOException
*/
public static void sendMessage(Gmail service, String userId, MimeMessage email)
throws MessagingException, IOException {
Message message = createMessageWithEmail(email);
message = service.users().messages().send(userId, message).execute();
System.out.println("Message id: " + message.getId());
System.out.println(message.toPrettyString());
}
/**
* Create a Message from an email
*
* @param email Email to be set to raw of message
* @return Message containing base64url encoded email.
* @throws IOException
* @throws MessagingException
*/
public static Message createMessageWithEmail(MimeMessage email)
throws MessagingException, IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
email.writeTo(bytes);
String encodedEmail = Base64.encodeBase64URLSafeString(bytes.toByteArray());
Message message = new Message();
message.setRaw(encodedEmail);
return message;
}
/**
* Modify the labels a message is associated with.
*
* @param service Authorized Gmail API instance.
* @param userId User's email address. The special value "me"
* can be used to indicate the authenticated user.
* @param messageId ID of Message to Modify.
* @param labelsToAdd List of label ids to add.
* @param labelsToRemove List of label ids to remove.
* @throws IOException
*/
public static void modifyMessage(Gmail service, String userId, String messageId,
List<String> labelsToAdd, List<String> labelsToRemove) throws IOException {
ModifyMessageRequest mods = new ModifyMessageRequest().setAddLabelIds(labelsToAdd)
.setRemoveLabelIds(labelsToRemove);
Message message = service.users().messages().modify(userId, messageId, mods).execute();
System.out.println("Message id: " + message.getId());
System.out.println(message.toPrettyString());
}
/**
* Create a MimeMessage using the parameters provided.
*
* @param to Email address of the receiver.
* @param from Email address of the sender, the mailbox account.
* @param subject Subject of the email.
* @param bodyText Body text of the email.
* @return MimeMessage to be used to send email.
* @throws MessagingException
*/
public static MimeMessage createEmail(String to, String from, String subject,
String bodyText) throws MessagingException {
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
MimeMessage email = new MimeMessage(session);
InternetAddress tAddress = new InternetAddress(to);
InternetAddress fAddress = new InternetAddress(from);
email.setFrom(new InternetAddress(from));
email.addRecipient(javax.mail.Message.RecipientType.TO,
new InternetAddress(to));
email.setSubject(subject);
email.setText(bodyText);
return email;
}
/**
*从用户邮箱向其收件人发送电子邮件。
*
*@param服务授权Gmail API实例。
*@param userId用户的电子邮件地址。“我”的特殊价值
*可用于指示经过身份验证的用户。
*@param要发送的电子邮件。
*@MessaginException
*@抛出异常
*/
公共静态void sendMessage(Gmail服务、字符串userId、mimessage电子邮件)
抛出MessaginException、IOException{
消息消息=createMessageWithEmail(电子邮件);
message=service.users().messages().send(userId,message).execute();
System.out.println(“消息id:+Message.getId());
System.out.println(message.toPrettyString());
}
/**
*从电子邮件创建消息
*
*@param电子邮件要设置为原始邮件
*@包含base64url编码电子邮件的返回消息。
*@抛出异常
*@MessaginException
*/
公共静态消息createMessageWithEmail(MimeMessage电子邮件)
抛出MessaginException、IOException{
ByteArrayOutputStream字节=新建ByteArrayOutputStream();
email.writeTo(字节);
String encodedEmail=Base64.encodeBase64URLSafeString(bytes.toByteArray());
消息消息=新消息();
message.setRaw(encodedmail);
返回消息;
}
/**
*修改邮件关联的标签。
*
*@param服务授权Gmail API实例。
*@param userId用户的电子邮件地址。“我”的特殊价值
*可用于指示经过身份验证的用户。
*@param messageId要修改的消息的ID。
*@param labels添加要添加的标签ID列表。
*@param labels删除要删除的标签ID列表。
*@抛出异常
*/
公共静态void modifyMessage(Gmail服务、字符串userId、字符串messageId、,
List labelsToAdd,List labelsToRemove)引发IOException{
ModifyMessageRequest mods=新建ModifyMessageRequest()。setAddLabelId(labelsToAdd)
.SetRemovelabelides(标签移动);
Message Message=service.users().messages().modify(userId,messageId,mods.execute();
System.out.println(“消息id:+Message.getId());
System.out.println(message.toPrettyString());
}
/**
*使用提供的参数创建mimessage。
*
*@param到收件人的电子邮件地址。
*@param来自发件人的电子邮件地址,邮箱帐户。
*@param邮件的主题。
*@param bodyText电子邮件的正文。
*@return mimessage用于发送电子邮件。
*@MessaginException
*/
公共静态MimeMessage createEmail(字符串到、字符串从、字符串主题、,
字符串bodyText)引发MessaginException{
Properties props=新属性();
Session Session=Session.getDefaultInstance(props,null);
MimeMessage email=新MimeMessage(会话);
InternetAddress tAddress=新的InternetAddress(收件人);
InternetAddress fAddress=新的InternetAddress(来自);
email.setFrom(新互联网地址(from));
email.addRecipient(javax.mail.Message.RecipientType.TO,
新互联网地址(至);;
email.setSubject(主题);
email.setText(bodyText);
回复邮件;
}
在Android中,您必须能够允许用户选择帐户。在droid的新平台中,您还必须另外请求他们允许您使用帐户的凭据,您可以在活动和清单中这样做。我在下面的例子中也是这样做的:
public class ContactsActivity extends Activity {
GoogleAccountCredential mCredential;
private TextView mOutputText;
ProgressDialog mProgress;
public static String accountName;
static final int REQUEST_ACCOUNT_PICKER = 1000;
static final int REQUEST_AUTHORIZATION = 1001;
static final int REQUEST_GOOGLE_PLAY_SERVICES = 1002;
private static final String PREF_ACCOUNT_NAME = "accountName";
private static final String[] SCOPES = {GmailScopes.GMAIL_LABELS,GmailScopes.GMAIL_SEND,GmailScopes.GMAIL_COMPOSE,GmailScopes.GMAIL_INSERT,GmailScopes.MAIL_GOOGLE_COM};
public static Gmail mService;
/**
* Create the main activity.
*
* @param savedInstanceState previously saved instance data.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout activityLayout = new LinearLayout(this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
activityLayout.setLayoutParams(lp);
activityLayout.setOrientation(LinearLayout.VERTICAL);
activityLayout.setPadding(16, 16, 16, 16);
ViewGroup.LayoutParams tlp = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
mOutputText = new TextView(this);
mOutputText.setLayoutParams(tlp);
mOutputText.setPadding(16, 16, 16, 16);
mOutputText.setVerticalScrollBarEnabled(true);
mOutputText.setMovementMethod(new ScrollingMovementMethod());
activityLayout.addView(mOutputText);
mProgress = new ProgressDialog(this);
mProgress.setMessage("Calling Gmail API ...");
setContentView(activityLayout);
int permissionCheck = ContextCompat.checkSelfPermission(this,
Manifest.permission.GET_ACCOUNTS);
// Initialize credentials and service object.
SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
mCredential = GoogleAccountCredential.usingOAuth2(getApplicationContext(), Arrays.asList(SCOPES))
.setBackOff(new ExponentialBackOff())
.setSelectedAccountName(settings.getString(PREF_ACCOUNT_NAME, null));
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.GET_ACCOUNTS},729);
}
/**
* Called whenever this activity is pushed to the foreground, such as after
* a call to onCreate().
*/
@Override
protected void onResume() {
super.onResume();
if (isGooglePlayServicesAvailable()) {
refreshResults();
} else {
mOutputText.setText("Google Play Services required: " +
"after installing, close and relaunch this app.");
}
}
/**
* Called when an activity launched here (specifically, AccountPicker
* and authorization) exits, giving you the requestCode you started it with,
* the resultCode it returned, and any additional data from it.
*
* @param requestCode code indicating which activity result is incoming.
* @param resultCode code indicating the result of the incoming
* activity result.
* @param data Intent (containing result data) returned by incoming
* activity result.
*/
@Override
protected void onActivityResult(
int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_GOOGLE_PLAY_SERVICES:
if (resultCode != RESULT_OK) {
isGooglePlayServicesAvailable();
}
break;
case REQUEST_ACCOUNT_PICKER:
if (resultCode == RESULT_OK && data != null &&
data.getExtras() != null) {
accountName =
data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null) {
mCredential.setSelectedAccountName(accountName);
SharedPreferences settings =
getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(PREF_ACCOUNT_NAME, accountName);
editor.apply();
}
} else if (resultCode == RESULT_CANCELED) {
mOutputText.setText("Account unspecified.");
}
break;
case REQUEST_AUTHORIZATION:
if (resultCode != RESULT_OK) {
chooseAccount();
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
/**
* Attempt to get a set of data from the Gmail API to display. If the
* email address isn't known yet, then call chooseAccount() method so the
* user can pick an account.
*/
private void refreshResults() {
mCredential.setSelectedAccountName("jennifer.ijcg@gmail.com");
if (mCredential.getSelectedAccountName() == null) {
chooseAccount();
} else {
if (isDeviceOnline()) {
new MakeRequestTask(mCredential).execute();
} else {
mOutputText.setText("No network connection available.");
}
}
}
/**
* Starts an activity in Google Play Services so the user can pick an
* account.
*/
private void chooseAccount() {
startActivityForResult(
mCredential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
}
/**
* Checks whether the device currently has a network connection.
*
* @return true if the device has a network connection, false otherwise.
*/
private boolean isDeviceOnline() {
ConnectivityManager connMgr =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
return (networkInfo != null && networkInfo.isConnected());
}
/**
* Check that Google Play services APK is installed and up to date. Will
* launch an error dialog for the user to update Google Play Services if
* possible.
*
* @return true if Google Play Services is available and up to
* date on this device; false otherwise.
*/
private boolean isGooglePlayServicesAvailable() {
final int connectionStatusCode =
GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (GooglePlayServicesUtil.isUserRecoverableError(connectionStatusCode)) {
showGooglePlayServicesAvailabilityErrorDialog(connectionStatusCode);
return false;
} else if (connectionStatusCode != ConnectionResult.SUCCESS) {
return false;
}
return true;
}
/**
* Display an error dialog showing that Google Play Services is missing
* or out of date.
*
* @param connectionStatusCode code describing the presence (or lack of)
* Google Play Services on this device.
*/
void showGooglePlayServicesAvailabilityErrorDialog(
final int connectionStatusCode) {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(
connectionStatusCode,
ContactsActivity.this,
REQUEST_GOOGLE_PLAY_SERVICES);
dialog.show();
}
/**
* An asynchronous task that handles the Gmail API call.
* Placing the API calls in their own task ensures the UI stays responsive.
*/
private class MakeRequestTask extends AsyncTask<Void, Void, List<String>> {
private Exception mLastError = null;
public MakeRequestTask(GoogleAccountCredential credential) {
HttpTransport transport = AndroidHttp.newCompatibleTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
mService = new com.google.api.services.gmail.Gmail.Builder(
transport, jsonFactory, credential)
.setApplicationName("RUOkay")
.build();
}
/**
* Background task to call Gmail API.
*
* @param params no parameters needed for this task.
*/
@Override
protected List<String> doInBackground(Void... params) {
try {
sendEmail();
return null; //getDataFromApi();
} catch (Exception e) {
mLastError = e;
cancel(true);
return null;
}
}
private void sendEmail() throws IOException {
// Get the labels in the user's account.
MimeMessage mimeMessage = null;
Message message = null;
String user = "jennifer.ijcg@gmail.com";
try {
mimeMessage = SendMail.createEmail("test@gmail.com",user,"u figured it out","your awesome");
} catch (MessagingException e) {
e.printStackTrace();
}
try {
message = SendMail.createMessageWithEmail(mimeMessage);
}
catch (MessagingException e) {
e.printStackTrace();
}
// mService.users().messages().send(user, message);
try {
SendMail.sendMessage(mService, user, mimeMessage);
} catch (MessagingException e) {
e.printStackTrace();
}
}
@Override
protected void onPreExecute() {
mOutputText.setText("");
mProgress.show();
}
@Override
protected void onPostExecute(List<String> output) {
mProgress.hide();
if (output == null || output.size() == 0) {
mOutputText.setText("No results returned.");
} else {
output.add(0, "Data retrieved using the Gmail API:");
mOutputText.setText(TextUtils.join("\n", output));
}
}
@Override
protected void onCancelled() {
mProgress.hide();
if (mLastError != null) {
if (mLastError instanceof GooglePlayServicesAvailabilityIOException) {
showGooglePlayServicesAvailabilityErrorDialog(
((GooglePlayServicesAvailabilityIOException) mLastError)
.getConnectionStatusCode());
} else if (mLastError instanceof UserRecoverableAuthIOException) {
startActivityForResult(
((UserRecoverableAuthIOException) mLastError).getIntent(),
ContactsActivity.REQUEST_AUTHORIZATION);
} else {
mOutputText.setText("The following error occurred:\n"
+ mLastError.getMessage());
}
} else {
mOutputText.setText("Request cancelled.");
}
}
}
公共类ContactsActivity扩展活动{
谷歌会计凭证;
私有文本视图mOutputText;
进步;
公共静态字符串accountName;
静态最终整数请求\帐户\选择器=1000;
静态最终int请求_授权=1001;
静态最终整数请求\谷歌\播放\服务=1002;
私有静态最终字符串PREF\u ACCOUNT\u NAME=“accountName”;
私有静态最终字符串[]SCOPES={GmailScopes.GMAIL_标签,GmailScopes.GMAIL_发送,GmailScopes.GMAIL_组合,GmailScopes.GMAIL_插入,GmailScopes.MAIL_谷歌_COM};
公共静态Gmail mService;
/**
*创建主活动。
*
*@param savedInstanceState以前保存的实例数据。
*/
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
LinearLayout activityLayout=新的LinearLayout(此);
LinearLayout.LayoutParams lp=新的LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_父级,
LinearLayout.LayoutParams.MATCH_PARENT);
activityLayout.setLayoutParams(lp);
活动布局。设置方向(线性布局。垂直);
activityLayout.setPadding(16,16,16,16);
ViewGroup.LayoutParams tlp=新建ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_内容,
ViewGroup.LayoutParams.WRAP_内容);
mOutputText=新文本视图(此);
MoutText.setLayoutParams(tlp);
moutput.setPadding(16,16,16,16);
MoutText.setVerticalScrollBarEnabled(真);
MoutText.setMovementMethod(新的ScrollingMovementMethod());
activityLayout.addView(mouttext);
mpprogress=新建进度对话框(此对话框);
setMessage(“调用Gmail API…”);
setContentView(活动布局);
int permissionCheck=ContextCompat.checkSelfPermi