📜  从 java spring boot 发送 gmail - Java (1)

📅  最后修改于: 2023-12-03 15:36:13.674000             🧑  作者: Mango

从Java Spring Boot发送Gmail - Java

在Java Spring Boot中发送Gmail是非常简单的,只需要按照以下步骤即可。

步骤1:在Google Cloud Console中启用Gmail API
  1. 登录Google Cloud Console:https://console.cloud.google.com/
  2. 创建新项目(如果没有现有项目)。如果已有一个项目,请转到第3步。
  3. 转到“API和服务”>“库”,并搜索“Gmail API”。
  4. 点击“启用”按钮以启用该API。
  5. 如果您还没有创建OAuth 2.0客户端ID,则需要创建一个。单击“创建凭据”,然后选择“OAuth客户端ID”选项。在下一步中,选择应用类型“其他”,并提供应用名称。单击“创建”后,将生成客户端ID和客户端密钥。将这些详细信息记录在安全的位置。
步骤2:添加依赖项

在您的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>
步骤3:编写Java代码

编写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刷新令牌。
步骤4:运行应用程序

运行该应用程序以使用Gmail API发送电子邮件。这应该简单快捷!

结论

现在您已经知道如何在Java Spring Boot中使用Gmail API发送电子邮件了!请务必仔细阅读步骤,确保设置正确并且代码可正常运行。