📅  最后修改于: 2023-12-03 15:36:13.674000             🧑  作者: Mango
在Java Spring Boot中发送Gmail是非常简单的,只需要按照以下步骤即可。
在您的Java Spring Boot项目中,添加以下Maven依赖项:
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-gmail</artifactId>
<version>v1-rev83-1.25.0</version>
</dependency>
<dependency>
<groupId>com.google.oauth-client</groupId>
<artifactId>google-oauth-client</artifactId>
<version>1.31.0</version>
</dependency>
<dependency>
<groupId>com.google.oauth-client</groupId>
<artifactId>google-oauth-client-jetty</artifactId>
<version>1.31.0</version>
</dependency>
编写Java代码以使用Gmail API发送电子邮件。以下是一个示例:
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.gmail.model.Message;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Collections;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class GmailApplication {
public static void main(String[] args) throws IOException, MessagingException {
SpringApplication.run(GmailApplication.class, args);
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
// Replace with your own credentials obtained from the Google Cloud Console
String clientId = "YOUR_CLIENT_ID.apps.googleusercontent.com"; // your client ID
String clientSecret = "YOUR_CLIENT_SECRET"; // your client secret
String refreshToken = "YOUR_REFRESH_TOKEN"; // your refresh token
// Build the credentials object
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setClientSecrets(clientId, clientSecret)
.build()
.setFromTokenResponse(new GoogleCredential
.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setClientSecrets(clientId, clientSecret)
.build()
.setRefreshToken(refreshToken)
.execute()
.getAccessToken());
// Build the Gmail object
Gmail service = new Gmail.Builder(httpTransport, jsonFactory, credential)
.setApplicationName("Gmail API Example")
.build();
// Create the email message
MimeMessage emailContent = new MimeMessage(Session.getDefaultInstance(Collections.emptyMap(), null));
emailContent.setFrom(new InternetAddress("me@example.com"));
emailContent.setRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress("friend@example.com"));
emailContent.setSubject("Test email from Java Spring Boot");
emailContent.setText("This is a test email sent from Java Spring Boot using Gmail API.");
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
emailContent.writeTo(buffer);
byte[] bytes = buffer.toByteArray();
String encodedEmail = com.google.api.client.util.Base64.encodeBase64URLSafeString(bytes);
Message message = new Message();
message.setRaw(encodedEmail);
// Send the email
service.users().messages().send("me", message).execute();
// Print confirmation message
System.out.println("Email sent successfully!");
}
}
替换以下代码:
YOUR_CLIENT_ID
- 您在第一步中创建的OAuth 2.0客户端ID。YOUR_CLIENT_SECRET
- 您在第一步中生成的OAuth 2.0客户端密钥。YOUR_REFRESH_TOKEN
- 您在第一步中获取的OAuth 2.0刷新令牌。运行该应用程序以使用Gmail API发送电子邮件。这应该简单快捷!
现在您已经知道如何在Java Spring Boot中使用Gmail API发送电子邮件了!请务必仔细阅读步骤,确保设置正确并且代码可正常运行。