Visualizzazione dei risultati da 1 a 2 su 2
  1. #1
    Utente di HTML.it
    Registrato dal
    Mar 2008
    Messaggi
    5

    utilizzare javamail per inviare mail con autorizzazione

    Quello che voglio fare è abbastanza facile da spiegare a parole, vorrei avere la possiblità di spedire dei messaggi di posta elettronica con java.
    Ho trovato questa classe sul forum

    codice:
    import javax.mail.*;
    import java.util.*;
    import javax.mail.internet.*;
    import javax.activation.*;
    import java.io.*;
    
    
    public class javamaildemo {
      String host = ".........."; //tuo smtp
      String from = "..........."; //tuo indirizzo email
      String ToAddress = "........"; //destinatario
      String user = "...........";
      String pass = "........";
      
      public javamaildemo() {
        try {
          //initialize the StringBuffer object within the try/catch loop
          StringBuffer sb = new StringBuffer( );
          
          //Get system properties
          Properties props = System.getProperties( );
        
          //Setup mail server
          props.put("mail.smtp.host", host);
          props.put("mail.debug", "true");
          props.put("mail.smtp.auth","true");
    
          //Get session
          Session session = Session.getDefaultInstance(props, null);
          session.setDebug(true);
          session.setPasswordAuthentication(new URLName("smtp",host,25,"INBOX",user,pass), new PasswordAuthentication(user,pass));
    
          //Define message
          MimeMessage msg = new MimeMessage(session);
          //Set the from address
          msg.setFrom(new InternetAddress(from));
          //Set the to address
          msg.addRecipient(Message.RecipientType.TO, new InternetAddress(ToAddress));
          //Set the subject
          msg.setSubject("Test mail using JavaMail APIs");
          //Set the text content for body
          sb.append("This is the 1st String line.\n\n");
          sb.append("This is the 2nd String line.\n\n");
          sb.append("This is the 3rd String line.\n\n");
          msg.setText(sb.toString( ));  
          //Send message
          Transport tr = session.getTransport("smtp");
          tr.connect(host, user, pass);
          msg.saveChanges(); // don't forget this
          tr.sendMessage(msg, msg.getAllRecipients());
          tr.close();
        }
        catch (MessagingException e) {
          System.out.println(e);
        }
      } 
    
    }
    ho bisogno dell'autenticazione non avendo un server smtp!!

    La classe viene lanciata da una servlet tramite:

    codice:
    javamaildemo jv = new javamaildemo();
    Il problema è che la classe mi genera un eccezione
    javax.mail.MessagingException: Could not connect to SMTP host
    i parametri che ho inserito sono
    host = "out.virgilio.it" oppure host ="smtp.gmail.com"
    ma con nessuna delle due funziona!
    Dove sbaglio?

  2. #2
    Utente di HTML.it
    Registrato dal
    Aug 2002
    Messaggi
    8,013
    Ciao, questo codice che sto postando è uno snellimento dell'originale incluso in JavaMail 1.4 tra le demo (smtpsend.java). Funziona con l'autenticazione con yahoo

    codice:
    import java.io.*;
    import java.net.InetAddress;
    import java.util.Properties;
    import java.util.Date;
    
    import javax.mail.*;
    import javax.mail.internet.*;
    
    import com.sun.mail.smtp.*;
    
    public class SendMailSMTP {
        
        private String mailer = "SendMailSMTP";
        private String prot = "smtps";
        private String mailhost = "smtp.mail.yahoo.com";
        private boolean auth = true;
        private boolean debug = true;
        private boolean verbose = false;
        private String user = "user_name_su_yahoo";
        private String password = "relativa_password";
        
        private String from = "TuoNome Via JavaMail <tuo_indirizzo@yahoo.it>";
        private String to = "AltroNome <altro_indirizzo@whatever.com>";
        private String subject = "An email from Java Mail";
    
        public SendMailSMTP() throws Exception {
            Properties props = System.getProperties();
            if (mailhost != null) {
                props.put("mail." + prot + ".host", mailhost);
            }
            if (auth) {
                props.put("mail." + prot + ".auth", "true");
            }
            
            Session session = Session.getInstance(props, null);
            if (debug) {
                session.setDebug(true);
            }
            
            // construct the message
            Message msg = new MimeMessage(session);
            if (from != null) {
                msg.setFrom(new InternetAddress(from));
            }
            else {
                msg.setFrom();
            }
            
            msg.setRecipients(Message.RecipientType.TO,
    					InternetAddress.parse(to, false));
    	/*if (cc != null) {
                msg.setRecipients(Message.RecipientType.CC,       
    					InternetAddress.parse(cc, false));
            }
            if (bcc != null) {
                msg.setRecipients(Message.RecipientType.BCC,        
    					InternetAddress.parse(bcc, false));
            }*/
            
            msg.setSubject(subject);
            String text = "This message was sent via Java Mail\n Testing the"+
                    " authentication features of the new version, JavaMail 1.4";
            
            msg.setText(text);
            
            SMTPTransport t =
    		(SMTPTransport)session.getTransport(prot);
    	try {
                if (auth)
                    t.connect(mailhost, user, password);
                else
                    t.connect();
                t.sendMessage(msg, msg.getAllRecipients());
            } 
            finally {
                if (verbose)
                    System.out.println("Response: " + t.getLastServerResponse());
                t.close();
            }
            
            msg.setHeader("X-Mailer", mailer);        
            msg.setSentDate(new Date());
            
            System.out.println("\nMail was sent successfully.");
            
        }
    
        public static void main(String[] argv) {
            
            try {
                new SendMailSMTP();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }    
    }
    funziona parimenti bene con gmail, ti basta usare la login per un tuo account gmail e modificare
    codice:
    private String mailhost = "smtp.mail.yahoo.com";
    in
    codice:
    private String mailhost = "smtp.gmail.com";
    Ovviamente così come è scritta è una porcata di classe, però dovrebbe darti un'idea di come procedere (vorrai costruttori in grado di accettare quei benedetti parametri di cui all'inizio)
    <´¯)(¯`¤._)(¯`»ANDREA«´¯)(_.¤´¯)(¯`>
    "The answer to your question is: welcome to tomorrow"

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2026 vBulletin Solutions, Inc. All rights reserved.