为什么在发送包含Gmail服务的电子邮件时会出现IOException?

时间:2014-08-17 12:25:38

标签: google-api google-oauth gmail-api

在我的Android测试应用程序中,之后我从谷歌开发者控制台获得了JSON文件,我在Gmail API上设置了该文件,并且我将它放在模拟器中,我得到一个IOException,其中说:

  

“com.google.api.client.googleapis.json.GoogleJsonResponseException:   403 Forbidden {“code”:403,“errors”:[{       “domain”:“usageLimits”,       “消息”:“未配置访问权限。请使用Google Developers Console激活项目的API。”,       “reason”:“accessNotConfigured”}],“message”:“未配置访问权限。请使用Google Developers Console激活API   为你的项目。“}”

我认为我必须使用GoogleClientSecrets对象,但我还没有找到它的用途。

这里是代码:

public class MainActivity extends Activity 
{   
    final String SCOPE = "oauth2:https://www.googleapis.com/auth/gmail.compose";
    final String FILE_NAME = "TestEmail5.json";
    private static final int REQUEST_RESOLVE_ERROR = 1001;

    Button button;

    OnClickListener sendListener = new OnClickListener()
    {

        @Override
        public void onClick(View v) 
        {
            new sendEmailTask().execute();

        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button)findViewById(R.id.button1);
        button.setOnClickListener(sendListener);


    }


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


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


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


    public class sendEmailTask extends AsyncTask
    {

        @Override
        protected Object doInBackground(Object... params)
        {
            HttpTransport httpTransport = new NetHttpTransport();
            JsonFactory jsonFactory = new JacksonFactory();
            String token = "";

            AccountManager accountManager = AccountManager.get(MainActivity.this);
            Account account[] = accountManager.getAccountsByType("com.google");

            String accountName = account[0].name;

            try 
            {
                //GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(jsonFactory,  new java.io.FileReader(Environment.getExternalStorageDirectory().getAbsolutePath() + "//" + "JSON/" + FILE_NAME));


                token = GoogleAuthUtil.getToken(MainActivity.this, accountName, SCOPE);

                GoogleCredential credential = new GoogleCredential().setAccessToken(token);

                Gmail service =  new Gmail.Builder(httpTransport, jsonFactory, credential).setApplicationName("TestEmail5").build();

                MimeMessage mm = createEmail("myemail", "myemail", "soggetto", "oggetto");

                sendMessage(service, "myemail", mm);

            } 
            catch (UserRecoverableAuthException e) 
            {
                startActivityForResult(e.getIntent(), REQUEST_RESOLVE_ERROR);
            } 
            catch (IOException e) 
            {
                e.printStackTrace();
            } 
            catch (GoogleAuthException e) 
            {
                e.printStackTrace();
            } 
            catch (MessagingException e)
            {
                e.printStackTrace();
            }


            return null;
        }

    };







}

1 个答案:

答案 0 :(得分:1)