Sending Email Using the Gmail API And Java

แชร์
ฝัง
  • เผยแพร่เมื่อ 10 ธ.ค. 2024

ความคิดเห็น • 113

  • @otwock2
    @otwock2 11 หลายเดือนก่อน +6

    Thank you, Sebastian! It's scary how much code one needs to write nowadays to send plain e-mail. You've made a really good guide here.

  • @JayJayMunich
    @JayJayMunich ปีที่แล้ว +2

    Ich hab gestern 6H versucht den Auth Prozess zum laufen zu bringen. 30 Minuten TH-cam Video und es funktioniert!

  • @끼리코덤보
    @끼리코덤보 4 หลายเดือนก่อน

    You solved what I didn't solve for two days. You are so amazing, thank you!!

  • @eliaspfeffer
    @eliaspfeffer ปีที่แล้ว +4

    how the fuck can someone tipe so fast? Im a fast typer but this guy is nuts, mad respect

    • @eliaspfeffer
      @eliaspfeffer ปีที่แล้ว +2

      Oh Ive just realised the speed was on 1.25 lol

  • @marufahmed7020
    @marufahmed7020 9 หลายเดือนก่อน +1

    thanks. the way you explained is easy to learn 💜

  • @otwock2
    @otwock2 11 หลายเดือนก่อน +2

    My previous comment disappeared. The problem is that Google gives you token/credentials that is valid only for 7 days when application is in "test" status. And making an application public is another story.

  • @odetireddipavan5906
    @odetireddipavan5906 2 ปีที่แล้ว +1

    In java 8 how to use set.of(GMAIL_SEND) scope?

    • @SebastianDaschnerIT
      @SebastianDaschnerIT  2 ปีที่แล้ว

      You can't, that method was added in JDK 9. You can use Collections.singleton() instead

  • @sachinacharya6740
    @sachinacharya6740 6 หลายเดือนก่อน +1

    bro you are amazing 🤩

  • @renatorsanti
    @renatorsanti 2 หลายเดือนก่อน

    How to open the consent url directly in the browser instead of showing it in the console???

  • @bekuostudio
    @bekuostudio 2 ปีที่แล้ว +5

    Thank you so much, Google Cloud Documentation is a pain in the ass

    • @GrantMitchell-f2p
      @GrantMitchell-f2p 9 หลายเดือนก่อน

      Indeed it is, make sure if you find something off to attach a ticket for them to update it which keeps the docs updated for everyone. :)

  • @TalhaBsbyk
    @TalhaBsbyk 3 หลายเดือนก่อน

    Do you really not use any more dependencies? I had to go to maven repository and download another .jar file for every other Alt+Enter you made. Do you maybe have an overarching library which has all of those included?

  • @sudheer312007
    @sudheer312007 11 หลายเดือนก่อน

    Will there be any expiry for the StoredCredential file that is getting generated ?

    • @GrantMitchell-f2p
      @GrantMitchell-f2p 9 หลายเดือนก่อน

      No, unless you revoke it or put a time limit on a key file.

  • @ProjectHandler-b7p
    @ProjectHandler-b7p 9 หลายเดือนก่อน

    I followed this guide however, after 7 days the token expired. How would i renew it? i did take a new json file from the credential page but still gets 400 error "Invalid_grant" token expired error.

    • @SebastianDaschnerIT
      @SebastianDaschnerIT  9 หลายเดือนก่อน

      it might be that the Google library creates a subfolder in your directory for the tokens that you need to delete, you might want to check for that

  • @weixiangng8279
    @weixiangng8279 ปีที่แล้ว

    How secure is the Gmail API for sending emails out in Spring Boot application?

    • @GrantMitchell-f2p
      @GrantMitchell-f2p 9 หลายเดือนก่อน

      Very if you follow all the steps in the docs.

  • @neny002
    @neny002 2 ปีที่แล้ว

    How to make it work for production? I get problem with Receiver. In google cloud project i have set redirect uri as app url, but local receiver has host as localhost, and i get error missmatch. But, if i match host same as redirect uri, i get error on backend that host cannot be set. So i dont know what to do.

    • @SebastianDaschnerIT
      @SebastianDaschnerIT  2 ปีที่แล้ว

      You can change the localhost receiver url in the code (IIRC that was documented somewhere) to make that work there (but then, also the extra port or URL has to be publicly reachable...), or you copy your credentials file to your production env (I've done that before), or you have access to the google admin console (I think you need a GSuite account) and can use the service account secrets (with domain-wide delegation). Sorry that the Google auth is a bit of a complex thing :)

    • @neny002
      @neny002 2 ปีที่แล้ว

      @@SebastianDaschnerIT Yea I figure it out that is complex.... So complicated... Thanks anyway

  • @vandanapatel5884
    @vandanapatel5884 8 หลายเดือนก่อน

    Thank you, Sebastian! great I am able to send mail but Can show us How to create Draft and Draft with Attachment using Google API in Java?

  • @LESBAU
    @LESBAU 11 หลายเดือนก่อน

    Could you make another video with an example of how to store the credential file in a database (preferably mongoDB) and how to use refreshToken to renew accesToken?

    • @GrantMitchell-f2p
      @GrantMitchell-f2p 9 หลายเดือนก่อน

      DO NOT DO THAT.

    • @GrantMitchell-f2p
      @GrantMitchell-f2p 9 หลายเดือนก่อน

      The JSON file is just an example. You would not deploy an application like this. You would use environment variables or GCLI when deploying an application.

  • @vidhipatel565
    @vidhipatel565 ปีที่แล้ว

    I'm using the code for the Android app but getting a runtime error. can you help me?

  • @RadekD-i8l
    @RadekD-i8l 10 หลายเดือนก่อน

    Thank You, Sebastian! Is there any way to send message in html?
    Thank You!!!

    • @SebastianDaschnerIT
      @SebastianDaschnerIT  10 หลายเดือนก่อน

      Yes, sure. If you use Quarkus/some framework, you can also combine a templating engine such as Qute to send HTML. For the sender it makes little difference, it just depends how the email program displays the HTML then.

  • @TimoDJatomika
    @TimoDJatomika ปีที่แล้ว

    Hello, as you said in the video you store the credentials in a directory "tokens". In this directory there is a crypted file which stores the credentials. Is there another way to store credentials or parse credentials to the application. I already have an access token and a refresh token that I would like to use.

    • @SebastianDaschnerIT
      @SebastianDaschnerIT  ปีที่แล้ว +1

      Yes, this definitely works. The only confusing bit is that there are multiple (competing) libs from Google side. If you use my example project, search for a `GoogleCredential` class, which unfortunately is deprecated, but if that's not an issue for you then this works. The deprecation notice also points you to a google-auth-library-java project, which also implements this, but I don't have any example code for that right now...

    • @TimoDJatomika
      @TimoDJatomika ปีที่แล้ว

      @@SebastianDaschnerIT Thanks a lot. GoogleCredential works for me.
      val depricatedGoogleCredential = GoogleCredential.Builder()
      .setTransport(httpTransport)
      .setJsonFactory(jsonFactory)
      .setClientSecrets(apiKeys["GOOGLE_CLIENT_ID"], apiKeys["GOOGLE_CLIENT_SECRET"])
      .build()
      .setAccessToken(apiKeys["GOOGLE_ACCESS_TOKEN"])
      .setRefreshToken(apiKeys["GOOGLE_REFRESH_TOKEN"])

    • @TimoDJatomika
      @TimoDJatomika ปีที่แล้ว

      code is in kotlin :)

    • @SebastianDaschnerIT
      @SebastianDaschnerIT  ปีที่แล้ว

      Great!

    • @sudheer312007
      @sudheer312007 11 หลายเดือนก่อน

      @@TimoDJatomika this code is working for me even without sending the access token . Am i missing something here ? please help

  • @odetireddipavan5906
    @odetireddipavan5906 2 ปีที่แล้ว

    I didn't understand how did you resolve those errors because when I was trying ALT+Enter it asking so many other options instead import packages and in those options import packages option is not there. Please help me here to get it done

    • @SebastianDaschnerIT
      @SebastianDaschnerIT  2 ปีที่แล้ว

      Probably a Maven resolution issue with your IDE. You can try the example project linked here: blog.sebastian-daschner.com/entries/sending-emails-gmail-api-java This should work.

  • @Karthikeyan_11K
    @Karthikeyan_11K 11 หลายเดือนก่อน

    How can I automate this mail sending sir?

    • @GrantMitchell-f2p
      @GrantMitchell-f2p 9 หลายเดือนก่อน

      By automate what do you mean. You can write the code however you want. Just keep calling a function to send the mail as many times as you want.

  • @MaxSchroder-sf4vr
    @MaxSchroder-sf4vr 7 หลายเดือนก่อน

    funktioniert gut. Aber wie kann ich das token auf einem externen Server verifizieren? Da geht redirect localhost:8888 ja nicht

    • @SebastianDaschnerIT
      @SebastianDaschnerIT  7 หลายเดือนก่อน

      Dazu benötigt man evtl einen service account. Siehe developers.google.com/identity/protocols/oauth2/service-account (die domain-wide delegation funktioniert aber IIRC nur mit einem GSuite / Admin account)

  • @БойкоБожинов-в3я
    @БойкоБожинов-в3я ปีที่แล้ว

    Absolutely great.Thank you for the video !

  • @AlexanderGritsok
    @AlexanderGritsok ปีที่แล้ว

    I still have a question that I couldn't solve myself: how to use queries to get email with a specific header?
    E.g. I need one email with needed for me X-custom-header, but I couldn't make it work like:
    service.users().messages().list(ME).setQ("X-custom-header:someInt");

    • @SebastianDaschnerIT
      @SebastianDaschnerIT  ปีที่แล้ว

      Good question. I've tried this myself and couldn't list messages by specific headers, neither in the API nor in the Gmail search. This page support.google.com/mail/answer/7190?hl=en lists the available search criteria (what you can put into the `?q=` param), and a header isn't part of it. I think that's not possible that easily. Maybe a way would be to use a Gmail filter or functionality to put the message into a label...

  • @UdulaIndunil
    @UdulaIndunil ปีที่แล้ว +1

    Thank you very much. Save my day

  • @testtest-c4z
    @testtest-c4z ปีที่แล้ว

    Very good video, is there something that is not clear to me when I send an email using an API, it is not done through an SMTP server? How would it be sent in that case?

    • @SebastianDaschnerIT
      @SebastianDaschnerIT  ปีที่แล้ว

      This uses the GMail API offered by Google. It's also possible to access GMail via SMTP server, but that's a very different approach

  • @HuongNguyen-ks7yd
    @HuongNguyen-ks7yd 9 หลายเดือนก่อน

    How about read an email, can you share the code for reading received email 😄

  • @ShadOmen
    @ShadOmen ปีที่แล้ว

    22:10 part how to do that?

    • @SebastianDaschnerIT
      @SebastianDaschnerIT  ปีที่แล้ว

      That's navigating a directory in Zsh (with some Tab expansions and I think an alias). This video should explain this: th-cam.com/video/j9g-VfKnkoU/w-d-xo.html

  • @geziraunited
    @geziraunited ปีที่แล้ว

    can you tell me gmail api limitation
    how many emails i can send

    • @SebastianDaschnerIT
      @SebastianDaschnerIT  ปีที่แล้ว

      developers.google.com/gmail/api/reference/quota

    • @geziraunited
      @geziraunited ปีที่แล้ว

      @@SebastianDaschnerIT
      are you app working with this requirements as below
      Ability to send emails to a list of email addresses (unlimited)
      Ability to set different subjects for a series of emails
      Ability to set different content for a series of emails
      Ability to send emails with text template
      Offering reports on the success or failure of each email
      Ability to determine pause between emails
      Ability to use multiple gmail api accounts for sending emails
      Ability to set the number of emails sent per account
      Ability to switch accounts
      Ability to switch proxies

  • @prathishkv5127
    @prathishkv5127 ปีที่แล้ว

    how to change the sender gmail? It is defautly taking my gmail.

  • @emiragovic2321
    @emiragovic2321 ปีที่แล้ว

    Can you use this code to send email to someone else or just yourself?

    • @SebastianDaschnerIT
      @SebastianDaschnerIT  ปีที่แล้ว

      Both. For sending it to yourself the "insert" functionality and permission into your mailbox would be sufficient, but both works.

    • @akashdebnath0107
      @akashdebnath0107 8 หลายเดือนก่อน

      I changed me to someone else's email ID but but it is throwing permission error could you please help me to resolve that?

  • @GmCodeJava
    @GmCodeJava ปีที่แล้ว +1

    Thank you for that !! Amzing !

  • @Zebsy
    @Zebsy ปีที่แล้ว +2

    Not easy, is it!

  • @Elliot-7972
    @Elliot-7972 ปีที่แล้ว

    When I run the code, I get:
    java.lang.RuntimeException: Unable to start activity ComponentInfo ...: java.lang.RuntimeException: java.io.IOException: unable to create directory: /tokens
    Am I supposed to create this folder, or maybe an android application (aka assets instead of res) needs another approach?

    • @GrantMitchell-f2p
      @GrantMitchell-f2p 9 หลายเดือนก่อน

      I am not going to bully you on this but it's kind of self explanatory. It is looking at the path /tokens which is in the resource folder. If you don't see it then you do not have the tokens folder which means you need to make it. :)

  • @TalDulberg
    @TalDulberg ปีที่แล้ว +1

    Great video thank you so much!

  • @monikaivettherczeg720
    @monikaivettherczeg720 ปีที่แล้ว

    Thank you Sir! 🤗

  • @mrmrdefmr
    @mrmrdefmr ปีที่แล้ว +1

    What are the differences between using Gmail api as u did and the sending via smtp ?
    If there is any benefit can you explain them.
    Thank you, Emre

    • @SebastianDaschnerIT
      @SebastianDaschnerIT  ปีที่แล้ว +1

      Good question :) I guess the API offers the full Gmail features (some of which might not be in the SMTP protocol) if we're talking about one's own account. For impersonating users I think this is only possible via API... If you already have a working smtp access then just sending yourself (or someone) an email might be not worth it to switch that to the API, but in general (starting from zero) I found it easier to integrate the API access into an application.

    • @otwock2
      @otwock2 ปีที่แล้ว +1

      As of 2023 you cannot send an e-mail from a program using SMTP and using Gmail if you have a basic, free Google account. I think Google has inaccurate (old) documentation on this topic. Anyway, I tried the SMTP approach and I'm getting the error: "535-5.7.8 Username and Password not accepted."

    • @GrantMitchell-f2p
      @GrantMitchell-f2p 9 หลายเดือนก่อน

      @@otwock2 You would use App password as the password for say like Node Mailer or Javax Mail API.

    • @otwock2
      @otwock2 9 หลายเดือนก่อน

      @@GrantMitchell-f2p App passwords are no longer supported by Google when using free account. When did you tried creating app password in Google last time?

    • @alexandru4626
      @alexandru4626 9 หลายเดือนก่อน

      @@GrantMitchell-f2pthis works in 2024? Meaning javax library and the app generated google password? Because I still get some errors when using it in android. On STMP Tool online ot works tho..

  • @RaffaGOD
    @RaffaGOD 7 หลายเดือนก่อน +1

    Thank you!!

  • @harixxxx
    @harixxxx 2 ปีที่แล้ว

    Does this work in an android app?

    • @SebastianDaschnerIT
      @SebastianDaschnerIT  2 ปีที่แล้ว

      Kind of. Yes it would work, but if you distribute it to others, that's likely not what you want, since then those users had access to your token (and email account). For accessing email on behalf of a user, they need to go through the OAuth thing, then. If you only create an app for yourself it works.

    • @harixxxx
      @harixxxx 2 ปีที่แล้ว

      @@SebastianDaschnerIT Thanks. This would be for personal use. Since gmail app is already on the phone, isn't there a way to have your app have gmail app send the email? The important thing for me is that it should happen without any user interaction (no UI involved), as my app will need to run forever in the background.

    • @SebastianDaschnerIT
      @SebastianDaschnerIT  2 ปีที่แล้ว

      Yes, these will be some questions to solve; I'm not an Android expert, but what I'd do is to have a minimal working example with Gmail just as plain Java (in your IDE), and then have a minimum android app example that does the job (and just log it first) and the put everything together and insert it into the app secondly.

    • @harixxxx
      @harixxxx 2 ปีที่แล้ว +1

      @@SebastianDaschnerIT Followed a different video & got sending ermail by directly connecting to google's SMTP server working. Downside is you need your gmail username/password in the app. Should be ok for personal use. The other risk is you never know when google will pull the plug on allowing their smtp server to be used. But for now something is working for sending email on android. It's a sms-to-email-forward app. Thanks for your responses!

    • @thechhotabheem
      @thechhotabheem ปีที่แล้ว

      @@SebastianDaschnerITso then what could be done to make an app that could be distributed publicly?.. I want to retrieve the user's emails in the app using the api.

  • @tarushdey18
    @tarushdey18 2 ปีที่แล้ว

    i need help

  • @eduardovalencia7274
    @eduardovalencia7274 2 ปีที่แล้ว +4

    excelente video fue de mucha ayuda

  • @nipundhananjaya-6537
    @nipundhananjaya-6537 ปีที่แล้ว

    Thank you very much bro!!!

  • @selimsezer3629
    @selimsezer3629 ปีที่แล้ว

    How can i send HTML template

    • @SebastianDaschnerIT
      @SebastianDaschnerIT  ปีที่แล้ว

      For the MIME message you can set html / multipart and then add your HTML content. Java Text blocks help here or templating approaches like Quarkus Qute

    • @selimsezer3629
      @selimsezer3629 ปีที่แล้ว

      ​@@SebastianDaschnerIT Hi again, you wrote Set.of(GMAIL_SEND) at minute 25:03 line 46 but when I write this code , I'm getting "no found interface" error. How can i solve this

    • @SebastianDaschnerIT
      @SebastianDaschnerIT  ปีที่แล้ว

      You need Java 9 + for Set.of() and to import static com.google.api.services.gmail.GmailScopes.GMAIL_SEND for the field. You can check out my code on GitHub: blog.sebastian-daschner.com/entries/sending-emails-gmail-api-java

    • @selimsezer3629
      @selimsezer3629 ปีที่แล้ว

      @@SebastianDaschnerIT Ok, thank you

  • @tarushdey18
    @tarushdey18 2 ปีที่แล้ว

    what about java with ant

    • @XPyCT_HOCKOB
      @XPyCT_HOCKOB 2 ปีที่แล้ว +1

      Don't use ant! It so old

    • @SebastianDaschnerIT
      @SebastianDaschnerIT  2 ปีที่แล้ว

      You'd have to look into some content how to build Java sources with dependencies (that you'd need to fetch from somewhere). The dependencies are stated in my pom.xml and you can also download them directly from Maven central. Good luck with ant ;)

  • @kiranpreetkaurgrewal2410
    @kiranpreetkaurgrewal2410 2 หลายเดือนก่อน

    You speak like Gabriel from Emily in Paris.

  • @jalen8430
    @jalen8430 ปีที่แล้ว

    Hey,
    I am getting this error "Exception in thread "main" java.lang.NullPointerException
    at java.base/java.io.Reader.(Reader.java:168)
    at java.base/java.io.InputStreamReader.(InputStreamReader.java:76)"
    Can you please help me?

    • @GrantMitchell-f2p
      @GrantMitchell-f2p 9 หลายเดือนก่อน

      Do you ever read the error and look it up? Not trying to be a hard ass even tho I am lol. But seriously it is an exception saying some variable you put in the inputstream is null or something is null. Check to see if you missed a step when it comes to setting a variable.

    • @samidowu6690
      @samidowu6690 2 หลายเดือนก่อน

      You probably figured it out, but when you get a Null Pointer exception, in this case you are trying to access a file(credential.json file) that doesn't exist. You have to set the proper path for your file. @jalen8430

    • @zeroTurn100
      @zeroTurn100 2 หลายเดือนก่อน

      I had this same problem, and to the "hard asses out there", reading the error and looking it up doesn't help. I too was confused about the location of a file accessed by GMailer.class.GetResourceAsStream(). So, because InputStreamReader's constructor simply wants any InputStream, I replaced getResourceAsStream() with new FileInputStream("path to your json file"). And it worked. Otherwise, this video was excellent.

  • @radugusanu5854
    @radugusanu5854 2 ปีที่แล้ว

    Can you help me with this please ?
    Exception in thread "main" java.lang.NullPointerException
    at java.base/java.io.Reader.(Reader.java:168)
    at java.base/java.io.InputStreamReader.(InputStreamReader.java:76)
    at com.cydeo.GMailer.getCredentials(GMailer.java:55)
    at com.cydeo.GMailer.(GMailer.java:45)
    at com.cydeo.GMailer.main(GMailer.java:107)

    • @SebastianDaschnerIT
      @SebastianDaschnerIT  2 ปีที่แล้ว

      Seems the credentials file isn't at the expected location?

  • @ahmedivy
    @ahmedivy 2 ปีที่แล้ว

    Exception in thread "main" java.lang.NoClassDefFoundError: sun/misc/ServiceConfigurationError
    at com.sun.net.httpserver.HttpServer.create(HttpServer.java:110)
    at com.google.api.client.extensions.jetty.auth@1.34.1/com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver.getRedirectUri(LocalServerReceiver.java:127)
    at com.google.api.client.extensions.java6.auth@1.34.1/com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp.authorize(AuthorizationCodeInstalledApp.java:109)
    This error is not going anywhere. I was using jdk17 first, it shows that error then i use jdk18, error is still there.
    How can i solve this?

    • @SebastianDaschnerIT
      @SebastianDaschnerIT  2 ปีที่แล้ว

      Can you try with the same dependencies I was using here: blog.sebastian-daschner.com/entries/sending-emails-gmail-api-java ?

    • @ahmedivy
      @ahmedivy 2 ปีที่แล้ว

      @@SebastianDaschnerIT I was using same your dependencies. It shows some error about library com.sun.net.httpserver . I was searching from 2 days on internet but didn't find answer

    • @SebastianDaschnerIT
      @SebastianDaschnerIT  2 ปีที่แล้ว

      Did you build and run just my project as a reproducer? I'm suspecting that your setup introduces some other dependencies that collide. If you start from a working example and then try to reproduce it, you should be able to find out what's causing it

    • @ahmedivy
      @ahmedivy 2 ปีที่แล้ว

      @@SebastianDaschnerIT at first i was trying in my project, it didn't work, then i created a new project with only those dependencies, it still not works.

    • @ahmedivy
      @ahmedivy 2 ปีที่แล้ว

      @@SebastianDaschnerIT there is some problem with com.sun module. I saw something on internet that may be this module is not available after java 8

  • @MrX4p
    @MrX4p ปีที่แล้ว

    can i connect with you for jobs give me your telegram