从文件中读取内容并发送电子邮件

时间:2014-01-15 20:26:41

标签: java nullpointerexception

我无法从文件中读取内容并将其作为java中的电子邮件正文发送。但是,如果我运行代码发送电子邮件而不从文件中读取内容,它会成功发送电子邮件,但在从正文文件中读取内容时会出现问题。如果你可以帮助我下面是我正在使用的代码

,那将是很棒的

提前致谢!

package com.example.tests;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class sendEmail {

    private static String USER_NAME = "zxxzz@gmail.com";  // GMail user name (just the part before "@gmail.com")
    private static String PASSWORD = "xxxxxxx"; // GMail password
    private static String RECIPIENT = "zxxzz@gmail.com";
    static String strLine = null;
    public static void main(String[] args) {
        String from = USER_NAME;
        String pass = PASSWORD;
        String[] to = { RECIPIENT }; // list of recipient email addresses
        String subject = "Java send mail example";
        String body = strLine;

        readfile();
        sendFromGMail(from, pass, to, subject, body);
    }

    private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
        Properties props = System.getProperties();
        String host = "smtp.gmail.com";
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.user", from);
        props.put("mail.smtp.password", pass);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");

        Session session = Session.getDefaultInstance(props);
        MimeMessage message = new MimeMessage(session);

        try {
            message.setFrom(new InternetAddress(from));
            InternetAddress[] toAddress = new InternetAddress[to.length];

            // To get the array of addresses
            for( int i = 0; i < to.length; i++ ) {
                toAddress[i] = new InternetAddress(to[i]);
            }

            for( int i = 0; i < toAddress.length; i++) {
                message.addRecipient(Message.RecipientType.TO, toAddress[i]);
            }

            message.setSubject(subject);
            message.setText(body);
            Transport transport = session.getTransport("smtp");
            transport.connect(host, from, pass);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
        }
        catch (AddressException ae) {
            ae.printStackTrace();
        }
        catch (MessagingException me) {
            me.printStackTrace();
        }
    }


    public static void readfile(){    
        try{
            // Open the file that is the first 
            // command line parameter
            FileInputStream fstream = new FileInputStream("C:\\Sample.txt");
            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));

            //Read File Line By Line
            while ((strLine = br.readLine()) != null)   {
                // Print the content on the console
                System.out.println (strLine);
            }
            //Close the input stream
            in.close();
        }catch (Exception e){//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
    }
}

我得到例外:

          Exception in thread "main" java.lang.NullPointerException
        at org.apache.geronimo.mail.util.ASCIIUtil.isAscii(ASCIIUtil.java:47)
        at javax.mail.internet.MimeMessage.setText(MimeMessage.java:939)
        at javax.mail.internet.MimeMessage.setText(MimeMessage.java:932)
        at com.example.tests.sendEmail.sendFromGMail(sendEmail.java:55)
        at com.example.tests.sendEmail.main(sendEmail.java:25)

3 个答案:

答案 0 :(得分:1)

strLine为空!

您正在正确读取文件,但是对最后一个分配的文件进行循环播放

strLine = br.readLine()) != null

也许是无意中。

替换

        //Read File Line By Line
        while ((strLine = br.readLine()) != null)   {
            // Print the content on the console
            System.out.println (strLine);
        }

        //Read File Line By Line
        String line;
        strLine="";
        while ((line = br.readLine()) != null)   {
            // Print the content on the console
            strLine += line;
        }
        System.out.println (strLine);

或更好地使用string buffer

        //Read File Line By Line
        String line;
        StringBuffer buffer = new StringBuffer("");
        while ((line = br.readLine()) != null)   {
            // Print the content on the console
            buffer.append(line);
        }
        strLine = buffer .toSTring();
        System.out.println (strLine);

然后致电

sendFromGMail(from, pass, to, subject, strLine);

答案 1 :(得分:1)

嗯,首先,有@venergiac提到的内容......但是,在你的main函数中,你做了:

final String body = strLine;  // body = strLine = null
readfile();                   // initalise strLine
sendFromGMail(from, pass, to, subject, body);  // use body

基本上,您在初始化body = strLine之前设置strLine 。 您可能也希望切换这两行(或直接使用strLine作为sendFromGmail的参数?)。

顺便说一下,Java中的Code Convention for the Java Programming Language是对任何类名使用 CamelCase :我认为您应该使用它并将您的类sendEmail重命名为SendEmail:)

干杯!

答案 2 :(得分:0)

问题是,您的body变量始终为空。

在主要功能中,将String body = strLine;更改为String body = mailString;并使用其他全局变量,例如mailString,并将其填入readfile函数

StringBuffer mailStirng = new StringBuffer("");

    public static void main(String[] args) {
            String from = USER_NAME;
            String pass = PASSWORD;
            String[] to = { RECIPIENT }; // list of recipient email addresses
            String subject = "Java send mail example";
            readfile();
            String body = mailStirng.toString();
            sendFromGMail(from, pass, to, subject, body);
        }

    public static void readfile(){    
            try{
                // Open the file that is the first 
                // command line parameter
                FileInputStream fstream = new FileInputStream("C:\\Sample.txt");
                // Get the object of DataInputStream
                DataInputStream in = new DataInputStream(fstream);
                BufferedReader br = new BufferedReader(new InputStreamReader(in));

                //Read File Line By Line
                while ((strLine = br.readLine()) != null)   {
                    // Print the content on the console
                    mailString.append(strLine);
                }
                //Close the input stream
                in.close();
            }catch (Exception e){//Catch exception if any
                System.err.println("Error: " + e.getMessage());
            }
        }