使用指定电子邮件帐户使用 Gmail API 发送电子邮件
Sending emails with Gmail API with a specified email account
由于OAuth2.0协议,JavaMail通过Gmail SMTP发送邮件的方式不再适用。我无法从自己的 Google 帐户发送电子邮件,因为会出现身份验证问题。
我确实使用 OAuth2.0 设置了 Gmail API,但我意识到这需要用户使用他们自己的 Google 帐户登录。
我想通过我专门设置的 Google 帐户向他们发送电子邮件,而不是使用他们自己的帐户。
这可能吗?
这是我目前拥有的。
Gmail 快速入门
/** Application name. */
private static final String APPLICATION_NAME =
"Gmail API Java Quickstart";
/** Directory to store user credentials for this application. */
private static final java.io.File DATA_STORE_DIR = new java.io.File(
".credentials/gmail-java-quickstart");
/** Global instance of the {@link FileDataStoreFactory}. */
private static FileDataStoreFactory DATA_STORE_FACTORY;
/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY =
JacksonFactory.getDefaultInstance();
/** Global instance of the HTTP transport. */
private static HttpTransport HTTP_TRANSPORT;
/** Global instance of the scopes required by this quick start. */
private static final List<String> SCOPES =
Arrays.asList(GmailScopes.GMAIL_COMPOSE);
static {
try {
HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
} catch (Throwable t) {
t.printStackTrace();
System.exit(1);
}
}
/**
* Creates an authorized Credential object.
* @return an authorized Credential object.
* @throws IOException
*/
public static Credential authorize() throws IOException {
// Load client secrets.
InputStream in =
GmailQuickstart.class.getResourceAsStream("/project/update/client_secret.json");
GoogleClientSecrets clientSecrets =
GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow =
new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(DATA_STORE_FACTORY)
.setAccessType("offline")
.build();
Credential credential = new AuthorizationCodeInstalledApp(
flow, new LocalServerReceiver()).authorize("user");
System.out.println(
"Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
return credential;
}
/**
* Build and return an authorized Gmail client service.
* @return an authorized Gmail client service
* @throws IOException
*/
public static Gmail getGmailService() throws IOException {
Credential credential = authorize();
return new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME)
.build();
}
发送Gmail
public static void main (String[] args) {
String to = "Recipient Email";
String from = "Sender Email";
String subject = "Hello World";
String bodyText = "This is an automated message.";
try {
MimeMessage msg = createEmail(to, from, subject, bodyText);
GmailQuickstart gqs = new GmailQuickstart();
Gmail service = gqs.getGmailService();
sendMessage(service, "me", msg);
} catch (MessagingException ex) {
Logger.getLogger(SendGmail.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(SendGmail.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* 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;
}
/**
* 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;
}
/**
* 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());
}
我已经在 gmail 中完成了。为什么我们不能这样做Sample Code. Only thing you need to do is enable less secure app setting in gmail security settings less secure app
由于OAuth2.0协议,JavaMail通过Gmail SMTP发送邮件的方式不再适用。我无法从自己的 Google 帐户发送电子邮件,因为会出现身份验证问题。
我确实使用 OAuth2.0 设置了 Gmail API,但我意识到这需要用户使用他们自己的 Google 帐户登录。 我想通过我专门设置的 Google 帐户向他们发送电子邮件,而不是使用他们自己的帐户。
这可能吗?
这是我目前拥有的。
Gmail 快速入门
/** Application name. */
private static final String APPLICATION_NAME =
"Gmail API Java Quickstart";
/** Directory to store user credentials for this application. */
private static final java.io.File DATA_STORE_DIR = new java.io.File(
".credentials/gmail-java-quickstart");
/** Global instance of the {@link FileDataStoreFactory}. */
private static FileDataStoreFactory DATA_STORE_FACTORY;
/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY =
JacksonFactory.getDefaultInstance();
/** Global instance of the HTTP transport. */
private static HttpTransport HTTP_TRANSPORT;
/** Global instance of the scopes required by this quick start. */
private static final List<String> SCOPES =
Arrays.asList(GmailScopes.GMAIL_COMPOSE);
static {
try {
HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
} catch (Throwable t) {
t.printStackTrace();
System.exit(1);
}
}
/**
* Creates an authorized Credential object.
* @return an authorized Credential object.
* @throws IOException
*/
public static Credential authorize() throws IOException {
// Load client secrets.
InputStream in =
GmailQuickstart.class.getResourceAsStream("/project/update/client_secret.json");
GoogleClientSecrets clientSecrets =
GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow =
new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(DATA_STORE_FACTORY)
.setAccessType("offline")
.build();
Credential credential = new AuthorizationCodeInstalledApp(
flow, new LocalServerReceiver()).authorize("user");
System.out.println(
"Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
return credential;
}
/**
* Build and return an authorized Gmail client service.
* @return an authorized Gmail client service
* @throws IOException
*/
public static Gmail getGmailService() throws IOException {
Credential credential = authorize();
return new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME)
.build();
}
发送Gmail
public static void main (String[] args) {
String to = "Recipient Email";
String from = "Sender Email";
String subject = "Hello World";
String bodyText = "This is an automated message.";
try {
MimeMessage msg = createEmail(to, from, subject, bodyText);
GmailQuickstart gqs = new GmailQuickstart();
Gmail service = gqs.getGmailService();
sendMessage(service, "me", msg);
} catch (MessagingException ex) {
Logger.getLogger(SendGmail.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(SendGmail.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* 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;
}
/**
* 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;
}
/**
* 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());
}
我已经在 gmail 中完成了。为什么我们不能这样做Sample Code. Only thing you need to do is enable less secure app setting in gmail security settings less secure app