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

Gmail api客户端库无法向java发送电子邮件,java,gmail-api,google-api-java-client,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" }

我正在尝试使用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;
      }
请试试这个

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;
    }  
请试试这个

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;
    }  
在Gmail API调用中传递空字符串或“me”作为用户ID:

gmail.users().messages().send(“,message).execute()

在Gmail API调用中传递空字符串或“me”作为用户ID:


gmail.users().messages().send(“,message).execute()

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

所以,若您使用的是客户机库,那个么在执行时传递“me”或空字符串,如下所示

gmail.users().messages().send(“我”,message.execute()

如果您使用的是RESTAPI,那么使用

me/消息


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

所以,若您使用的是客户机库,那个么在执行时传递“me”或空字符串,如下所示

gmail.users().messages().send(“我”,message.execute()

如果您使用的是RESTAPI,那么使用

me/消息


欢迎使用堆栈溢出API SICOA!你能告诉我们你的相关代码在哪里发送邮件吗?用户id是否丢失或无效?这真是一个愚蠢的问题,在我看来,“userID”是无用的,并且与“from”属性混淆了。移除它,使它“从”和它的作品一直。谢谢大家的帮助和解答,欢迎来到Stack Overflow API SICOA!你能告诉我们你的相关代码在哪里发送邮件吗?用户id是否丢失或无效?这真是一个愚蠢的问题,在我看来,“userID”是无用的,并且与“from”属性混淆了。移除它,使它“从”和它的作品一直。谢谢大家的帮助和回答谢谢先生,我会在周一试试这个,然后留下反馈谢谢先生,我会在周一试试这个,然后留下反馈这从2018年起就不再起作用了(尽管过时的文件说它仍然起作用)。这从2018年起就不再起作用了(尽管过时的文件表明它仍然存在)。