【问题标题】:Gmail api client library cannot send email javaGmail api客户端库无法发送电子邮件java
【发布时间】:2016-01-06 02:28:49
【问题描述】:

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

【问题讨论】:

  • 欢迎使用 Stack Overflow API SICOA!您能否向我们展示您尝试发送邮件的相关代码?
  • 用户id是否丢失或无效?
  • 这真是一个愚蠢的问题,在我看来,“userID”是无用的,并且与“from”属性混淆了。将其删除,使其“来自”并且它可以正常工作。谢谢大家的帮助和解答

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


【解决方案1】:

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

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

【讨论】:

  • 这在 2018 年不再有效(尽管过时的文档说它仍然有效)。
【解决方案2】:

请试试这个

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

【讨论】:

  • 谢谢先生,我会在星期一试试这个并留下反馈
【解决方案3】:

一般来说,这种类型的错误发生在经过身份验证的电子邮件地址和来自电子邮件地址的未匹配发生时。

所以,如果您使用的是客户端库,请在执行时传递“me”或空字符串,如下所示

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

如果你使用的是rest api,那么使用

https://www.googleapis.com/gmail/v1/users/我/messages

【讨论】:

    猜你喜欢
    • 2016-02-18
    • 2018-09-11
    • 1970-01-01
    • 2021-09-11
    • 2013-02-03
    • 2022-01-13
    • 2021-05-23
    • 2012-07-07
    相关资源
    最近更新 更多