Reputation: 167
I am trying to send mail using Gmail java API. I am getting following Error.
Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
"code" : 403,
"errors" : [ {
"domain" : "global",
"message" : "Insufficient Permission",
"reason" : "insufficientPermissions"
} ],
"message" : "Insufficient Permission"
}
at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:145)
at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:111)
at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:38)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest$1.interceptResponse(AbstractGoogleClientRequest.java:314)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1060)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:412)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:345)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:463)
at GMailLibrary.SendEmail.sendMessage(SendEmail.java:32)
at GMailLibrary.GMailAuthentication.main(GMailAuthentication.java:85)
Java Result: 1
I have done the authentication part using Authentication code. Following is my piece of code for sending Email.
public class SendEmail
{
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 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 MimeMessage createEmailWithAttachment(String to, String from, String subject,String bodyText, String fileDir, String filename) throws MessagingException, IOException
{
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(fAddress);
email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress);
email.setSubject(subject);
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setContent(bodyText, "text/plain");
mimeBodyPart.setHeader("Content-Type", "text/plain; charset=\"UTF-8\"");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(mimeBodyPart);
mimeBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(fileDir + filename);
mimeBodyPart.setDataHandler(new DataHandler(source));
mimeBodyPart.setFileName(filename);
String contentType = Files.probeContentType(FileSystems.getDefault()
.getPath(fileDir, filename));
mimeBodyPart.setHeader("Content-Type", contentType + "; name=\"" + filename + "\"");
mimeBodyPart.setHeader("Content-Transfer-Encoding", "base64");
multipart.addBodyPart(mimeBodyPart);
email.setContent(multipart);
return email;
}
}
I am calling the SendMail methods from main class by passing the required information.
MimeMessage email = SendEmail.createEmail(to, from, subject, bodytext);
SendEmail.sendMessage(service, USER, email);
Please help me. I already tried my best. Let me know if any more information is required.
Upvotes: 1
Views: 4890
Reputation: 51
I had the same problem with listing messagesd. I tried to delete "StoredCredential" in ~/.credentials/gmail-api-quickstar but that wouldn't help. What you need is to set "GmailScopes" to MAIL_GOOGLE_COM that corresponds to the full permissions access.
/** Global instance of the scopes required by this quickstart. */
private static final List<String> SCOPES =
Arrays.asList(GmailScopes.MAIL_GOOGLE_COM);
Upvotes: 5
Reputation: 41
My problem was that I got Google's sample working with listing labels, then added the scope for composing, but it didn't work until I deleted the authentication in ~/.credentials/gmail-api-quickstart, then ran it again so that it opened a browser and I re-authenticated, this time with the compose permission.
Upvotes: 4
Reputation: 79
I had this same problem, first you have to configure your project in google developer console, and ON the gmail API, download the credentials and put it in your project, then you need to set up the service for connecting to the class send mail, This code works for me, you just have to authorize permission: I am already calling the class sendMail and using its methods. I hope it works for you. PD: Do not pay attention in class Name and other instances call Calendar, I have modified a Calendar Sample to using it with Gmail.
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.DataStoreFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.gmail.GmailScopes;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
public class CalendarSample {
/**
* Be sure to specify the name of your application. If the application name is {@code null} or
* blank, the application will log a warning. Suggested format is "MyCompany-ProductName/1.0".
*/
private static final String APPLICATION_NAME = "gmailProject";
/** Directory to store user credentials. */
private static final java.io.File DATA_STORE_DIR =
new java.io.File(System.getProperty("user.home"), ".store/gmail_sample");
/**
* Global instance of the {@link DataStoreFactory}. The best practice is to make it a single
* globally shared instance across your application.
*/
private static FileDataStoreFactory dataStoreFactory;
/** Global instance of the HTTP transport. */
private static HttpTransport httpTransport;
/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static com.google.api.services.gmail.Gmail gmailClient;
/** Authorizes the installed application to access user's protected data. */
private static Credential authorize() throws Exception {
// load client secrets
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
new InputStreamReader(CalendarSample.class.getResourceAsStream("/client_secrets.json")));
if (clientSecrets.getDetails().getClientId().startsWith("Enter")
|| clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
System.out.println(
"Enter Client ID and Secret from https://code.google.com/apis/console/?api=gmail "
+ "into calendar-cmdline-sample/src/main/resources/client_secrets.json");
System.exit(1);
}
// set up authorization code flow
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, JSON_FACTORY, clientSecrets,
Collections.singleton(GmailScopes.MAIL_GOOGLE_COM)).setDataStoreFactory(dataStoreFactory)
.build();
// authorize
return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}
public static void main(String[] args) {
try {
// initialize the transport
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
// initialize the data store factory
dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
// authorization
Credential credential = authorize();
// set up global Gmail instance
gmailClient = new com.google.api.services.gmail.Gmail.Builder(
httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build();
mailMethod();
} catch (IOException e) {
System.err.println(e.getMessage());
} catch (Throwable t) {
t.printStackTrace();
}
System.exit(1);
}
private static void mailMethod() throws IOException, MessagingException{
MyClass sendMail = new MyClass();
MimeMessage mail2;
mail2 = sendMail.createEmail("[email protected]", "[email protected]", "prueba de correo", "prueba de correo2");
System.out.println("Obtener MIME: " + mail2);
sendMail.sendMessage(gmailClient, "[email protected]", mail2);
}
}
Upvotes: 0
Reputation: 1037
Judging from the information you've given in your question, I'd say that you've set your permissions incorrectly as you need to Create
permissions to send messages. You can set your permissions correctly by:
CLIENT_SECRET_FILE = 'your client secret.json'
OAUTH_SCOPE = 'https://www.googleapis.com/auth/gmail.compose'
STORAGE = Storage('gmail.storage')
flow = flow_from_clientsecrets(CLIENT_SECRET_FILE, scope=OAUTH_SCOPE)
http = httplib2.Http()
credentials = STORAGE.get()
if credentials is None or credentials.invalid:
credentials = run(flow, STORAGE, http=http)
http = credentials.authorize(http)
gmail_service = build('gmail', 'v1', http=http)
This is how I set up my gmail API (though I have different permissions, because I don't send email via the API). If you can update your question to include your setup I'll be happy to update my answer.
Upvotes: 2