【问题标题】:How to send an email using Gmail API and Java如何使用 Gmail API 和 Java 发送电子邮件
【发布时间】:2014-12-14 16:55:10
【问题描述】:

我在 Openshift 上部署了一个 Web 服务。目前我正在开发的是一种在某个时间点使用我的 Gmail 帐户发送自动电子邮件的方法。

所以我已经记录了自己两三天,我得出的结论是我有两个选择:

1) 使用 JavaMail 库。 2) 使用 Gmail API。

对于第一个选项,我使用的是以下类:

public class EmailSenderService {  
private final Properties properties = new Properties();  

private String password = "*******";  

private Session session;  

private void init() {  

    //ssl
    properties.put("mail.smtp.host", "smtp.gmail.com");
    properties.put("mail.smtp.socketFactory.port", "465");
    properties.put("mail.smtp.socketFactory.class",
            "javax.net.ssl.SSLSocketFactory");
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.smtp.port", "465");

    session = Session.getDefaultInstance(properties,
        new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("eu***@gmail.com",password);
            }
        });
}  

public void sendEmail(){  

    init();  

    //ssl
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("eu***@gmail.com"));
        message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse("c***6@gmail.com"));
        message.setSubject("Testing Subject");
        message.setText("Dear Mail Crawler," +
                "\n\n No spam to my email, please!");
        Transport t = session.getTransport("smtp");
        t.connect("smtp.gmail.com", "eu***@gmail.com", password);
        t.sendMessage(message, message.getAllRecipients());

        System.out.println("Done");

    } catch (MessagingException e) {
        e.printStackTrace();
    }   
}  
} 

然后用这个来调用他们:

EmailSenderService ess = new EmailSenderService();
        ess.sendEmail();

2) 我使用的第二个选项如下:

public class EmailSenderGmailApi {

/*
 * Atributos
 */
// Check https://developers.google.com/gmail/api/auth/scopes for all available scopes
private static final String SCOPE = "https://www.googleapis.com/auth/gmail.compose";
private static final String APP_NAME = "eu***l";
// Email address of the user, or "me" can be used to represent the currently authorized user.
private static final String USER = "eu***@gmail.com";
// Path to the client_secret.json file downloaded from the Developer Console
private static final String CLIENT_SECRET_PATH = "../app-root/data/eu***.json";

private static GoogleClientSecrets clientSecrets;


/*
 * Metodos
 */

public static Gmail init() throws IOException{

    System.out.println("***Working Directory = " + System.getProperty("user.dir"));


    HttpTransport httpTransport = new NetHttpTransport();
    JsonFactory jsonFactory = new JacksonFactory();

    clientSecrets = GoogleClientSecrets.load(jsonFactory,  new FileReader(CLIENT_SECRET_PATH));

    // Allow user to authorize via url.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
        httpTransport, jsonFactory, clientSecrets, Arrays.asList(SCOPE))
        .setAccessType("online")
        .setApprovalPrompt("auto").build();

    String code = "***";

    // Generate Credential using retrieved code.
    GoogleTokenResponse response = flow.newTokenRequest(code)
        .setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI).execute();
    GoogleCredential credential = new GoogleCredential()
        .setFromTokenResponse(response);

    // Create a new authorized Gmail API client
    return new Gmail.Builder(httpTransport, jsonFactory, credential)
        .setApplicationName(APP_NAME).build();


}

/**
   * 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 {

      System.out.println("***Empezando a enviar email...");

    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 base64 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());
  }

}

第一个选项,调用它时,Openshift COnsole中显示的消息如下:

javax.mail.AuthenticationFailedException
    at javax.mail.Service.connect(Service.java:306)
    at javax.mail.Service.connect(Service.java:156)
    at main.java.model.EmailSenderService.sendEmail(EmailSenderService.java:86)
    at main.java.model.AccessManager.renewPassStepOne(AccessManager.java:234)
    at main.java.webService.UsuarioService.renewPassStepOne(UsuarioService.java:192)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
    at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:185)
    at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
    at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
    ...

我一直在尝试自己修复它,查看 google、stackoverflow...但是我引入的每一个更改,我得到的信息都是一样的。

在选项2中,我不知道如何使用它。我正在尝试这样的事情:

MimeMessage msg = EmailSenderGmailApi.createEmail("ca***@gmail.com", "eu***@gmail.com", "test", "holaaaaa");

        EmailSenderGmailApi.sendMessage(
                EmailSenderGmailApi.init(), 
                "cap***@gmail.com", 
                msg);

不管怎样,老实说我调查了很多Java Mail,希望有人能帮我解决我遇到的任何错误。

关于 Gmail Api,在官方文档中,我无法弄清楚如何发送电子邮件。互联网上也没有那么多文档。

有人可以帮我吗?

【问题讨论】:

    标签: email jakarta-mail google-oauth google-api-java-client gmail-api


    【解决方案1】:

    Gmail API 公共文档有发送电子邮件的指南,甚至还有 java 示例代码:

    https://developers.google.com/gmail/api/guides/sending

    不过,您上面的代码似乎并不遥远。我首先要确保 Oauth2 正常工作,方法是做一些简单的事情,比如 labels.list(),如果可行,然后继续做一些更复杂的事情,比如发送电子邮件。 (您有正确的想法构建、转换为字符串、base64url 编码然后发送它。)您在尝试使用 Gmail API 发送它时遇到的确切问题是什么?有错误输出或代码中缺少某些内容?

    【讨论】:

    • 谢谢。我这周去看看。如果我得到它,我会通知你。我的问题是我不知道如何创建“Gmail 服务”参数以在 sendMessage 中使用它。
    • 嗯,好的。应该与日历、驱动器等其他 Google API 相当标准,而且很可能是他们的入门/快速入门,表明它应该适用于具有适当替换的 Gmail。我会添加一些标签,希望能帮助更多人关注它。
    【解决方案2】:

    如果您在 openshift 应用程序中使用 Java Mail API,

    然后在应用程序中添加任何新库,您必须在 pom.xml 文件中添加其 maven-configuration。或者换句话说,你必须在 pom.xml 文件中添加依赖。

    这是 mail-1.4.7 的依赖项 只需将此代码添加到 pom.xml 文件中

    <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.7</version>
        </dependency>
    

    同样,对于任何其他集成,不要忘记添加依赖项。 你可以在谷歌搜索: “________的maven依赖”

    【讨论】:

      【解决方案3】:
      猜你喜欢
      • 1970-01-01
      • 2016-01-20
      • 2018-01-26
      • 2014-08-27
      • 2018-02-23
      • 2021-01-24
      • 2021-09-11
      • 2015-01-02
      • 2017-04-14
      相关资源
      最近更新 更多