Re: sending emails with authentication

Chris Burdess <[email protected]> Mon, 20 Sep 2010 08:40:24 +0100
Newsgroups gmane.comp.java.classpath.extensions.javamail
Message-ID <[email protected]>
Daniel Rindt wrote:
> Am Donnerstag, den 16.09.2010, 08:27 +0100 schrieb Chris Burdess:
>> The PrintStream(File) constructor specifically says that it won't
>> flush the underlying stream. You will need to call flush manually on
>> that PrintStream, or use the OutputStream constructor.
> Yes. But this is also not working:
> =3D=3D=3D 8< =3D=3D=3D
> 	Session session =3D Session.getInstance(props, auth);
> 	session.setDebug(true);
> 	PrintStream ps =3D null;
> 	try {
> 	    ps =3D new PrintStream("/tmp/classpathx-mail.out");
> 	    session.setDebugOut(ps);
> 	} catch (FileNotFoundException e) {
> 	    // TODO Auto-generated catch block
> 	    e.printStackTrace();
> 	}
> 	try {
> 	    Message msg =3D new MimeMessage(session);
> 	    msg.setFrom(new InternetAddress(senderAddress));
> 	    msg.setRecipients(Message.RecipientType.TO, =
InternetAddress.parse(
> 		    recipientsAddress, false));
> 	    msg.setSubject(subject);
> 	    msg.setText(text);
> 	    msg.saveChanges();
> 	    Transport.send(msg);
> 	} catch (Exception e) {
> 	    e.printStackTrace();
> 	}
> 	ps.flush();
> 	ps.close();
> =3D=3D=3D 8< =3D=3D=3D
> I got nothing in the file, its just zero bytes. Thanks for further =
help.


I amended your code and got it to work:

        Session session =3D Session.getInstance(props, auth);
        session.setDebug(true);
        OutputStream fos =3D null;
        try {
            fos =3D new FileOutputStream("classpathx-mail.out");
            PrintStream ps =3D new PrintStream(fos);
            session.setDebugOut(ps);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            Message msg =3D new MimeMessage(session);
            msg.setFrom(new InternetAddress(senderAddress));
            msg.setRecipients(Message.RecipientType.TO, =
InternetAddress.parse(
                    recipientsAddress, false));
            msg.setSubject(subject);
            msg.setText(text);
            msg.saveChanges();
            Transport.send(msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //fos.close();

Note that if you close the FileOutputStream at the end you won't get any =
output. This is down to some weirdness in exactly why/how/when =
PrintStreams get flushed, which I'm afraid I don't understand myself, =
but it's not a problem in the logging as far as I can see (which as I =
said simply uses the java.util.logging mechanism. If you find any way to =
shed any light on what's happening there please share it.

Regards
--=20
Chris Burdess