从oAuth认证的应用程序通过SMTP发送邮件所需的Android示例

时间:2012-04-16 02:55:11

标签: android oauth smtp gmail

我正在关注检索用户Gmail联系人的oAuth演示。我可以通过oAuth进行身份验证,并使联系人工作正常。

现在我想修改它以便能够通过SMTP发送电子邮件。我可以获得oAuth授权来做到这一点。

我的问题是我无法弄清楚下一步。在验证后,如何格式化发送电子邮件的请求。

我不希望有人为我编写代码,只是一个简单的链接到谷歌api文档,涵盖这应该让我去。我似乎无法找到它们。

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

我实际上也在研究这个问题。如果您可以通过OAuth进行身份验证,那么您只需通过OAuth通过Google的Gmail API即可使其正常运行。我让Gmail使用OAuth作为Java应用程序。但对于Android来说,谷歌提供的相同代码仅适用于SMTP(不是IMAP),这很有趣。但我想它仍然有用。

以下链接将引导您使用Google针对Gmail的OAuth协议: https://developers.google.com/google-apps/gmail/oauth_overview 他们准备好样品。确保准备好JavaMail和OAuth访问令牌。您不需要Apache Ant来运行其示例代码。我刚刚使用了eclipse并运行了主类。

另请注意,OAuth for Gmail略有不同。我不确定您是如何进行身份验证的,但对于Gmail, SCOPE 会有所不同:https://mail.google.com/如果您不知道, Scribe 将是一种非常方便的方式让OAuth在Java中工作。

答案 1 :(得分:0)

btnPreviewEmails.setOnClickListener(new OnClickListener()
{

    @Override
    public void onClick(View v) 
    {
        // TODO Auto-generated method stub
          String host="your smtp";
          final String user="from email address";//change accordingly
          final String password="frm email password";//change accordingly

          String to="to email";//change accordingly

           //Get the session object
           Properties props = new Properties();
           props.put("mail.smtp.host",host);
           props.put("mail.smtp.auth", "true");

           javax.mail.Session session = javax.mail.Session.getDefaultInstance(props,new javax.mail.Authenticator() {
                      protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
                    return new javax.mail.PasswordAuthentication(user,password);
                      }
                    });

                   //Compose the message
                    try {
                     MimeMessage message = new MimeMessage(session);
                     message.setFrom(new InternetAddress(user));
                     message.addRecipient(javax.mail.Message.RecipientType.TO,new InternetAddress(to));
                     message.setSubject("javatpoint");
                     message.setText("This is simple program of sending email using JavaMail API");

                    //send the message
                     javax.mail.Transport.send(message);

                     System.out.println("message sent successfully...");

                     } 
                    catch (MessagingException e) 
                    {
                        e.printStackTrace();
                        }
    }});
相关问题