Gmail api客户端库无法发送电子邮件java

时间:2015-10-08 12:46:41

标签: java gmail-api google-api-java-client

我正在尝试使用java客户端api发送电子邮件。无论我尝试什么,我都会得到这个json错误:

{
    "code": 403,
    "errors": [
        {
            "domain": "global",
            "message": "Invalid user id specified in request/Delegation denied",
            "reason": "forbidden"
        }
    ],
    "message": "Invalid user id specified in request/Delegation denied"
}

任何想法如何绕过这个错误??

与特定问题相关的代码,创建MIME消息,然后根据需要创建相应的消息:

@Path("/sendmessage/{to}/{from}/{subject}/{body}/{userID}")
    @GET
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public Response sendMessage(
            @PathParam("to")String to, 
            @PathParam("from") String from, 
            @PathParam("subject") String subject, 
            @PathParam("body") String body,
            @PathParam("userID") String userID)
    {
            MimeMessage mimeMessage =null;
                Message message = null;

                mimeMessage =createEmail(to, from, subject, body);
                message = createMessageWithEmail(mimeMessage);
                gmail.users().messages().send(userID,message).execute();
resp = Response.status(200).entity(message.toPrettyString()).build();

return resp;
}

public static MimeMessage createEmail(String to, String from, String subject, String bodyText){

          Properties props = new Properties();
          String host = "smtp.gmail.com";
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.user", from);
            props.put("mail.smtp.password", "******");
            props.put("mail.smtp.port", "587");
            props.put("mail.smtp.auth", "true");

            Session session = Session.getDefaultInstance(props);

          MimeMessage email = new MimeMessage(session);
          try{
            InternetAddress toAddress = new InternetAddress(to);
            InternetAddress fromAddress = new InternetAddress(from);

            email.setFrom(fromAddress);
            email.addRecipient(javax.mail.Message.RecipientType.TO, toAddress);
            email.setSubject(subject);
            email.setText(bodyText);

            Transport transport = session.getTransport("smtp");
            transport.connect(host, from, ********);
            transport.sendMessage(email, email.getAllRecipients());
            transport.close();
           }
           catch(Exception e){
               LOGGER.error("Class: "+className+", Method: "+methodName+", "+e.getMessage());

           }
            return email;
      }

 public static Message createMessageWithEmail(MimeMessage email){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            email.writeTo(baos);
        } catch (IOException | MessagingException e) {
            LOGGER.error("Class: "+className+", Method: "+methodName+", "+e.getMessage());
        }
        String encodedEmail = Base64.encodeBase64URLSafeString(baos.toByteArray());
        Message message = new Message();
        message.setRaw(encodedEmail);
        return message;
      }

3 个答案:

答案 0 :(得分:2)

传递空字符串或" me"作为Gmail API调用中的userId:

gmail.users().messages().send("", message).execute();

答案 1 :(得分:1)

请试试这个

public static boolean sendEmail(String subject,String to,String content, MultipartFile file,String filenameName) throws Exception{

        try{
            final String username = "***@gmail.com";
            final String password = "***";
            Properties props = new Properties();
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.host", "smtp.gmail.com");// For gmail Only U can change as per requirement
            props.put("mail.smtp.port", "587"); //Different port for different email provider 
            props.setProperty("mail.smtp.auth", "true");
            Session session = Session.getInstance(props,new javax.mail.Authenticator() {
                            protected PasswordAuthentication getPasswordAuthentication() {
                                return new PasswordAuthentication(username, password);
                            }   
            });
            session.setDebug(true);

            Message message = new MimeMessage(session);
            message.setHeader("Content-Type","text/plain; charset=\"UTF-8\"");
            message.setSentDate(new Date());
            message.setFrom(new InternetAddress(username));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            message.setSubject(subject);
            if(file!=null){
            //-Multipart Message
                Multipart multipart = new MimeMultipart();
            // Create the message part 
                BodyPart messageBodyPart = new MimeBodyPart();
                messageBodyPart.setText(content);
                multipart.addBodyPart(messageBodyPart);//Text Part Add
            // Part two is attachment
                messageBodyPart= new MimeBodyPart() ;
                ByteArrayDataSource source=new ByteArrayDataSource(file.getBytes(),"application/octet-stream");
                messageBodyPart.setDataHandler(new DataHandler(source));
                messageBodyPart.setFileName(filename);

                multipart.addBodyPart(messageBodyPart);
            //Send the complete message parts
                message.setContent(multipart);
            }
            else
                message.setText(content);
            //message.setText(content);
            Transport.send(message);
        }
        catch(Exception e){
            return false;
        }
        return true;
    }  

答案 2 :(得分:1)

通常,当经过身份验证的电子邮件地址和电子邮件地址未匹配时会发生此类错误。

因此,如果您正在使用客户端库,则在执行时传递“me”或空字符串,如下所示

  

gmail.users()。messages()。send(“me”,message).execute();

如果您使用的是rest api,请使用

  

https://www.googleapis.com/gmail/v1/users/ /消息