使用指定电子邮件帐户的Gmail API发送电子邮件

时间:2016-01-15 06:23:52

标签: java email oauth-2.0 gmail-api

由于OAuth2.0协议,JavaMail通过Gmail SMTP发送电子邮件的方式已不再适用。我无法从自己的Google帐户发送电子邮件,因为会出现身份验证问题。

我确实使用OAuth2.0设置了Gmail API,但我意识到这需要用户使用自己的Google帐户登录。 我想通过我专门设置但未使用自己帐户的Google帐户向他们发送电子邮件。

这可能吗?

这就是我目前所拥有的。

GmailQuickStart

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

SendGmail

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

1 个答案:

答案 0 :(得分:2)

我在gmail中完成了这个。为什么我们不能这样做Sample Code。您唯一需要做的就是在Gmail安全设置less secure app

中启用安全性较低的应用设置