Java - 字符串``''中的非法地址

时间:2015-05-25 21:10:32

标签: java swing email javamail

我有一个InternalFrame,我在其中设置邮件(来自),密码,邮件(到),主题和文本。

可运行代码:

package br.com.projekt.gui;

import java.util.Arrays;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class Mail extends javax.swing.JInternalFrame {

    private final String mailSMTPServer;
    private final String mailSMTPServerPort;

    public Mail() {
        initComponents();
        mailSMTPServer = "smtp.gmail.com";
        mailSMTPServerPort = "465";
    }

    public Mail(String mailSMTPServer, String mailSMTPServerPort) { //Para outro Servidor  
        this.mailSMTPServer = mailSMTPServer;
        this.mailSMTPServerPort = mailSMTPServerPort;
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        mail = new javax.swing.JTextField();
        senden = new javax.swing.JButton();
        betreff = new javax.swing.JTextField();
        empfanger = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        text = new javax.swing.JTextField();
        pass = new javax.swing.JPasswordField();

        jLabel1.setText("Mailadresse:");

        jLabel2.setText("Passwort:");

        senden.setText("Senden");
        senden.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendenActionPerformed(evt);
            }
        });

        jLabel3.setText("Empfänger:");

        jLabel4.setText("Betreff:");

        jLabel5.setText("Text:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(jLabel2)
                                .addComponent(jLabel3)
                                .addComponent(jLabel4)
                                .addComponent(jLabel5)))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(mail, javax.swing.GroupLayout.DEFAULT_SIZE, 232, Short.MAX_VALUE)
                            .addComponent(empfanger, javax.swing.GroupLayout.DEFAULT_SIZE, 251, Short.MAX_VALUE)
                            .addComponent(betreff, javax.swing.GroupLayout.DEFAULT_SIZE, 251, Short.MAX_VALUE)
                            .addComponent(text)
                            .addComponent(pass)))
                    .addComponent(senden))
                .addContainerGap(38, Short.MAX_VALUE))
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {betreff, empfanger, mail});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(49, 49, 49)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(mail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(pass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(empfanger, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(betreff, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(text, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
                .addComponent(senden)
                .addGap(29, 29, 29))
        );

        pack();
    }// </editor-fold>                        

    private void sendenActionPerformed(java.awt.event.ActionEvent evt) {                                       
        sendMail(mail.getText(), empfanger.getText(), betreff.getText(), text.getText());
    }                                      

    public void sendMail(String from, String to, String subject, String message) {

        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtp"); //define protocolo de envio como SMTP  
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", mailSMTPServer); //server SMTP do GMAIL  
        props.put("mail.smtp.auth", "true"); //ativa autenticacao  
        props.put("mail.smtp.user", mail.getText()); //usuario ou seja, a conta que esta enviando o email (tem que ser do GMAIL)  
        props.put("mail.debug", "true");
        props.put("mail.smtp.port", mailSMTPServerPort); //porta  
        props.put("mail.smtp.socketFactory.port", mailSMTPServerPort); //mesma porta para o socket  
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");

        SimpleAuth auth = null;
        auth = new SimpleAuth(mail.getText(), Arrays.toString(pass.getPassword()));

        Session session = Session.getDefaultInstance(props, auth);
        session.setDebug(true); //Habilita o LOG das ações executadas durante o envio do email  

        //Objeto que contém a mensagem  
        Message msg = new MimeMessage(session);

        try {
            //Setando o destinatário  
            msg.setRecipient(Message.RecipientType.TO, new InternetAddress(empfanger.getText()));
            //Setando a origem do email  
            msg.setFrom(new InternetAddress(mail.getText()));
            //Setando o assunto  
            msg.setSubject(betreff.getText());
            //Setando o conteúdo/corpo do email  
            msg.setContent(message, text.getText());

        } catch (Exception e) {
            System.out.println(">> Erro: Completar Mensagem");
            e.printStackTrace();
        }

        Transport tr;
        try {
            tr = session.getTransport("smtps"); 

            tr.connect(mailSMTPServer, mail.getText(), Arrays.toString(pass.getPassword()));
            msg.saveChanges(); 
            tr.sendMessage(msg, msg.getAllRecipients());
            tr.close();
        } catch (Exception e) {
            System.out.println(">> Erro: Envio Mensagem");
            e.printStackTrace();
        }

    }


    // Variables declaration - do not modify                     
    public static javax.swing.JTextField betreff;
    public static javax.swing.JTextField empfanger;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    public static javax.swing.JTextField mail;
    public static javax.swing.JPasswordField pass;
    private javax.swing.JButton senden;
    public static javax.swing.JTextField text;
    // End of variables declaration                   
}

运行程序的主要类:

public static void main(String args[]) {
        Mail sm = new Mail("smtp.gmail.com","465"); 
        sm.sendMail(Mail.mail.getText(), Mail.empfanger.getText(),Mail.betreff.getText(),Mail.text.getText());
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(HauptMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(HauptMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(HauptMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(HauptMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new HauptMenu().setVisible(true);
            }
        });
    }

通过gmail smtp。 认证课程:

package br.com.projekt.gui;

import java.util.Arrays;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

class SimpleAuth extends Authenticator {  
    public String username = null;  
    public String password = null;  
    Mail email = new Mail();

    public SimpleAuth(String user, String pwd) {  
        username = user;  
        password = pwd; 

    }  

    @Override
    public PasswordAuthentication getPasswordAuthentication() { 
        return new PasswordAuthentication ( Mail.mail.getText(),Arrays.toString(Mail.pass.getPassword()));  
    }  
}

通过jTextFields我提供了信息,但是因为我在运行时有一个空字段而得到了错误!

错误:

Connection Successfull
    DEBUG: JavaMail version 1.5.3
    DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
    DEBUG: Tables of loaded providers
    DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle]}
    DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]}
    DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
    DEBUG: setDebug: JavaMail version 1.5.3
    >> Erro: Completar Mensagem
    javax.mail.internet.AddressException: Illegal address in string ``''
    DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle]
    DEBUG SMTP: useEhlo true, useAuth false
    DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 465, isSSL true
        at javax.mail.internet.InternetAddress.<init>(InternetAddress.java:114)
        at br.com.projekt.gui.Mail.sendMail(Mail.java:148)
        at br.com.projekt.gui.Mail.sendenActionPerformed(Mail.java:120)
        at br.com.projekt.gui.Mail.access$000(Mail.java:11)
        at br.com.projekt.gui.Mail$1.actionPerformed(Mail.java:50)
        at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
        at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
        at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
        at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
        at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
        at java.awt.Component.processMouseEvent(Component.java:6525)
        at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
        at java.awt.Component.processEvent(Component.java:6290)
        at java.awt.Container.processEvent(Container.java:2234)
        at java.awt.Component.dispatchEventImpl(Component.java:4881)
        at java.awt.Container.dispatchEventImpl(Container.java:2292)
        at java.awt.Component.dispatchEvent(Component.java:4703)
        at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
        at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
        at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
        at java.awt.Container.dispatchEventImpl(Container.java:2278)
        at java.awt.Window.dispatchEventImpl(Window.java:2750)
        at java.awt.Component.dispatchEvent(Component.java:4703)
        at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
        at java.awt.EventQueue.access$500(EventQueue.java:97)
        at java.awt.EventQueue$3.run(EventQueue.java:709)
        at java.awt.EventQueue$3.run(EventQueue.java:703)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
        at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
        at java.awt.EventQueue$4.run(EventQueue.java:731)
        at java.awt.EventQueue$4.run(EventQueue.java:729)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
        at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
        at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
    com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.gmail.com, 465; timeout -1;
      nested exception is:
        java.net.ConnectException: Connection timed out: connect
    >> Erro: Envio Mensagem
        at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2054)
        at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:697)
        at javax.mail.Service.connect(Service.java:364)
        at javax.mail.Service.connect(Service.java:245)
        at br.com.projekt.gui.Mail.sendMail(Mail.java:165)
        at br.com.projekt.gui.Mail.sendenActionPerformed(Mail.java:120)
        at br.com.projekt.gui.Mail.access$000(Mail.java:11)
        at br.com.projekt.gui.Mail$1.actionPerformed(Mail.java:50)
        at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
        at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
        at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
        at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
        at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
        at java.awt.Component.processMouseEvent(Component.java:6525)
        at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
        at java.awt.Component.processEvent(Component.java:6290)
        at java.awt.Container.processEvent(Container.java:2234)
        at java.awt.Component.dispatchEventImpl(Component.java:4881)
        at java.awt.Container.dispatchEventImpl(Container.java:2292)
        at java.awt.Component.dispatchEvent(Component.java:4703)
        at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
        at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
        at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
        at java.awt.Container.dispatchEventImpl(Container.java:2278)
        at java.awt.Window.dispatchEventImpl(Window.java:2750)
        at java.awt.Component.dispatchEvent(Component.java:4703)
        at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
        at java.awt.EventQueue.access$500(EventQueue.java:97)
        at java.awt.EventQueue$3.run(EventQueue.java:709)
        at java.awt.EventQueue$3.run(EventQueue.java:703)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
        at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
        at java.awt.EventQueue$4.run(EventQueue.java:731)
        at java.awt.EventQueue$4.run(EventQueue.java:729)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
        at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
        at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
    Caused by: java.net.ConnectException: Connection timed out: connect
        at java.net.DualStackPlainSocketImpl.connect0(Native Method)
        at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
        at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:345)
        at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
        at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
        at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
        at java.net.Socket.connect(Socket.java:589)
        at java.net.Socket.connect(Socket.java:538)
        at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:329)
        at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:236)
        at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2020)
        ... 43 more

0 个答案:

没有答案