【发布时间】: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