Probleme mit javax.mail.Session

CConraths

Aktives Mitglied
Hallo Forum,
ich habe zwar für mein Problem Lösungsansätze im Web gefunden es hat jenes aber nicht geheilt.
Deswegen bitte ich euch mir zu helfen.
ich möchte aus meiner Anwendung heraus eine E-Mail senden.
Ich habe javax.mail.jar im classpath des Projekts eingebunden.
So sieht meine Klasse aus.


Java:
package hilfsklassen;
import java.util.Date;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class JavaMail {
    
    public static void main(String[] args) {
         sendEmail(prepareSession(), toGmail,"TLSEmail Testing Subject", "Balance > 100");
    }       
    
    private static Session  prepareSession() {           
         System.out.println("TLSEmail Start");
         Properties props = new Properties();
         props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host
         props.put("mail.smtp.port", "587"); //TLS Port
         props.put("mail.smtp.auth", "true"); //enable authentication
         props.put("mail.smtp.starttls.enable", "true"); //enable STARTTLS
        
         Authenticator auth = new Authenticator() {
             //override the getPasswordAuthentication method
             protected PasswordAuthentication getPasswordAuthentication() {
                 return new PasswordAuthentication(fromGmail, passwordGmail);
             }
         };
         return Session.getInstance(props, auth);   
        
    }

    public static void sendEmail(Session session, String toEmail, String subject, String body){
        try
        {       
         MimeMessage message = new MimeMessage(session);   
          //set message headers
          message.addHeader("Content-type", "text/HTML; charset=UTF-8");
          message.addHeader("format", "flowed");
          message.addHeader("Content-Transfer-Encoding", "8bit");
 
          message.setFrom(new InternetAddress(fromGmail, "NoReply-JD"));
 
          message.setReplyTo(new InternetAddress[]{new InternetAddress(toYahoo)});
 
          message.setSubject(subject, "UTF-8");
 
          message.setText(body, "UTF-8");
 
          message.setSentDate(new Date());
 
          message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toGmail, false));
          System.out.println("Message is ready");
          Transport.send(message); 
 
          System.out.println("EMail Sent Successfully!!");
        }
        catch (Exception e) {
          e.printStackTrace();
        }
    }
    static Session mySession;
    static final String fromGmail = "christianconraths11@gmail.com"; //requires valid gmail id
    static final String passwordGmail = "*****"; // correct password for gmail id
    static final String fromYahoo = "christian.conraths@yahoo.de"; //requires valid gmail id
    static final String passwordYahoo = "*****"; // correct password for gmail id
    static final String toGmail =  "christianconraths11@gmail.com";  // can be any email id
    static final String toYahoo =  "christian.conraths@yahoo.de";  // can be any email id
}


Und diesen Fehler bekomme ich zurückgemeldet

TLSEmail Start
Nov. 14, 2022 7:10:27 AM javax.mail.Session loadResource
WARNUNG: expected resource not found: /META-INF/javamail.default.address.map
Message is ready
javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8 https://support.google.com/mail/?p=BadCredentials x3-20020adfdd83000000b002366a624bd4sm8595052wrl.28 - gsmtp

at java.mail/com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:965)
at java.mail/com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:876)
at java.mail/com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:780)
at java.mail/javax.mail.Service.connect(Service.java:388)
at java.mail/javax.mail.Service.connect(Service.java:246)
at java.mail/javax.mail.Service.connect(Service.java:195)
at java.mail/javax.mail.Transport.send0(Transport.java:254)
at java.mail/javax.mail.Transport.send(Transport.java:124)
at Ipsos/hilfsklassen.JavaMail.sendEmail(JavaMail.java:52)
at Ipsos/hilfsklassen.JavaMail.main(JavaMail.java:10)

Username und Passwwort sind valide das habe ich mit GoogleMail Aufruf geprüft.
Im Web ist die rede von 2-Wege Authentifizierung die Probleme macht.
Die habe ich in meinem Google-Account inaktiv gesetzt.
Hilft nichts.

Was fehlt hier noch beim Session-Aufbau ???

Dank für jede Hilfe.
 
Ich weiss nicht, ob es das bei gmail auch gibt: In der GSuite kann man - so der Admin das für die Domain nicht unterbunden hat - Legacy Applikationen erstellen. Diese können dann mit User / Passwort zugreifen.
 
Danke erstmal für den Response.
In dem Thema merke ich wie weit ich da weg bin.
Ich verstehe das so
Wenn ich von aussen eine Mail auf meinem Google E-Mail Account generieren möchte muss zwingend die 2-Wege Authentifiezierung in meinem Google-Account aktiviert sein.
Google und Google-Mail werden mit demselben Passwort aufgerufen.
Wenn ich von Java aus eine Google-Mail versenden möchte nutze ich javax.mail.
So weit so gut.

Man kann den Connect und die Authentifizierung über einen SMTP oder einen IMAP-Server durchführen

Mein Versuch
Code:
 /**
           * Connects and authenticates to an IMAP server with OAuth2. You must have
           * called {@code initialize}.
           *
           * @param host Hostname of the imap server, for example {@code
           *     imap.googlemail.com}.
           * @param port Port of the imap server, for example 993.
           * @param userEmail Email address of the user to authenticate, for example
           *     {@code oauth@gmail.com}.
           * @param oauthToken The user's OAuth token.
           * @param debug Whether to enable debug logging on the IMAP connection.
           *
           * @return An authenticated IMAPStore that can be used for IMAP operations.
           */
          public static IMAPStore connectToImap(String host,
                                                int port,
                                                String userEmail,
                                                String oauthToken,
                                                boolean debug) throws Exception {
            Properties props = new Properties();
            props.put("mail.imaps.sasl.enable", "true");
            props.put("mail.imaps.sasl.mechanisms", "XOAUTH2");
            props.put(OAuth2SaslClientFactory.OAUTH_TOKEN_PROP, oauthToken);
            Session session = Session.getInstance(props);
            session.setDebug(debug);

            final URLName unusedUrlName = null;
            IMAPSSLStore store = new IMAPSSLStore(session, unusedUrlName);
            final String emptyPassword = "";
            store.connect(host, port, userEmail, emptyPassword);
            return store;
          }

Aufruf der Function

Code:
/**
           * Authenticates to IMAP with parameters passed in on the commandline.
           */
          public static void main(String args[]) throws Exception {
            if (args.length != 2) {
              System.err.println(
                  "Usage: OAuth2Authenticator <email> <oauthToken>");
              return;
            }
            String email = args[0];
            String oauthToken = args[1];

            initialize();

            IMAPStore imapStore = connectToImap("imap.gmail.com",
                                                993,
                                                email,
                                                oauthToken,
                                                true);
            System.out.println("Successfully authenticated to IMAP.\n");
          
          }
Nun meine Frage
1) Die Anweisung "props.put(OAuth2SaslClientFactory.OAUTH_TOKEN_PROP, oauthToken)" bringt den compilerfehler
Multiple markers at this line
- OAuth2SaslClientFactory cannot be resolved to a
variable
- OAUTH_TOKEN_PROP cannot be resolved or is
not a field
ich habe importiert

com.sun.mail.auth.OAuth2SaslClientFactory;

was fehlt ?

Danke fürs drüberschauen
 

Neue Themen


Zurück
Oben