★ wanayoo — archive 1999 http://developer.java.sun.com/developer/qow/archive/74/index.htmlNouvelle recherche | Portail wanayoo
Java Technology Home Page
A-Z Index

Java Developer Connection(SM)
Question of the Week

Downloads, APIs, Documentation
Java Developer Connection
Tutorials, Tech Articles, Training
Online Support
Community Discussion
News & Events from Everywhere
Products from Everywhere
How Java Technology is Used Worldwide
Print Button
 

Question of the Week No. 74

Researched by Sara Louis

Question of the Week presents answers to key questions posed by the developer community. The intent is to pass this important, but not always easy-to-find, information on to JavaTM Developer ConnectionSM (JDC) members. The questions are selected from the JDC Forums generally because: they are frequently asked, they are significant or timely, or the answers are not easily accessible.

Topic:   How can files be attached to e-mail using JavaMailTM?

Question:  

I am having trouble attaching files other than .txt files to e-mail. Has anyone done this before?

Answer:

Try this out:

aToAddress - address to be sent to
pSubject - subject of message
pMessage - the text message
pFileName - the name of the file to be attached.

Be sure to give the absolute path name starting from where the JavaTM Virtual Machine1 (JVM) is running.

                  
Message msg = new MimeMessage(session); 
   msg.setFrom( aDefaultFromAddress ); 
   InternetAddress[] address = {aToAddress}; 
   msg.setRecipients(
        Message.RecipientType.TO, address); 
   msg.setSubject( pSubject ); 
   msg.setSentDate(new java.util.Date()); 
   // create and fill the first message part 
   MimeBodyPart mbp1 = new MimeBodyPart(); 
   mbp1.setText(pMessage); 
   // create the second message part 
   MimeBodyPart mbp2 = new MimeBodyPart(); 
   // attach the file to the message 
   FileDataSource fds=
            new FileDataSource(pFileName); 
   mbp2.setDataHandler(
              new DataHandler(fds)); 
   mbp2.setFileName(pFileName); 
   // create the Multipart 
   //and its parts to it 
   Multipart mp = new MimeMultipart(); 
   mp.addBodyPart(mbp1); 
   mp.addBodyPart(mbp2); 
   // add the Multipart to the message 
   msg.setContent(mp); 
   Transport.send(msg); 
 

Many thanks to JDC member vsalelkar for contributing to this answer.

For More Information about JavaMail: JavaMail FAQ

Note: If you have a question to which you need an answer, try the JDC Forums. You can read through the existing topics, or with your free JDC membership, you can post new messages or threads.




Mon Feb 07 11:28:32 PST 2000
rolandsmom
How are different file types handled as attachments?

For example, .pdf files are currently base-64 encoded with a C program, then sent as attachments to a sendmail message. Is the base-64 encoding still necessary for a pdf attachment in JavaMail? If it is, does JavaMail provide encoding functionality?

Mon Feb 07 13:12:35 PST 2000
kpinky1
Hey Guys,
I have trouble using Java Mail API's from JSP pages. Please help.


I have a XYZMail class wirtten based upon the example sendmail. I am using JSP to instantiate that class set the properties and send the mail. But I get a null pointer exception. Although I have all the variables set.

Code for the Mail Object: <code>
import java.beans.*;
import java.util.*;
import java.io.*;
import javax.mail.*;

import javax.mail.internet.*;
import javax.activation.*;

public class XYZMail extends Object
implements java.io.Serializable {

private ArrayList mailTo
= new ArrayList();
private String mailFrom ;
private String mailSubject ;
private String mailMessage ;
private String mailHost;
private ArrayList mailAttachments = new ArrayList();
private Properties props;
private javax.mail.Session sess;
private InternetAddress[] address
= { new InternetAddress() };

public XYZMail() {
props = new Properties( ) ;
props = System.getProperties();
}

public long sendMail () throws MessagingException {

props.put("mail.smtp.host", getMailHost() );
sess = javax.mail.Session.getDefaultInstance(props, null);
sess.setDebug( Boolean.valueOf( "false" ).booleanValue() );

int i = 0;
MimeMessage msg = new MimeMessage(sess);

msg.setFrom(new InternetAddress( getMailFrom() ));
for ( Iterator itr = mailTo.iterator( ); itr.hasNext(); ) {
address[i] = new InternetAddress((String) itr.next()) ;
}


msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject( getMailSubject() );


MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText( getMailMessage() );

Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);

if ( ! mailAttachments.isEmpty() ) {
MimeBodyPart mbp2 = new MimeBodyPart();

FileDataSource fds=new FileDataSource( (String)
mailAttachments.get(0) );
mbp2.setDataHandler(new DataHandler(fds));
mbp2.setFileName( (String) mailAttachments.get(0) );
mp.addBodyPart(mbp2);
}

msg.setContent(mp);

msg.setSentDate(new Date());

Transport.send(msg);
return 1;
}



public ArrayList getMailTo ( ) {
return mailTo;
}

public String getMailFrom ( ) {
return mailFrom;
}

public String getMailSubject ( ) {
return mailSubject;
}

public String getMailMessage ( ) {
return mailMessage;
}

public ArrayList getMailAttachments ( ) {
return mailAttachments;
}

public String getMailHost ( ) {
return mailHost;
}

public void setMailHost ( String host ) {
mailHost = host;
}
public void setMailAttachments ( ArrayList attachments ) {
mailAttachments = attachments ;
}

public void setMailMessage ( String msg ) {
mailMessage = msg ;
}

public void setMailSubject ( String subject ) {
mailSubject = subject ;
}

public void setMailFrom ( String from ) {
mailFrom = from;
}

public void setMailTo ( ArrayList to ) {
mailTo = to;
}

}
<code>

Then I have the Jsp page which instantiates this object and sets all the values, but fails on the execution of the sendMail() method returning a NullPointerException. Although when I use a another test class it works

Thanks in Advance
Manoj

Mon Feb 07 18:11:47 PST 2000
[Member not logged in]
But how do I set the mime-type of the attached file? For example, I may want to set the mime-type to "application/vnd.ms-powerpoint". When the Java mail program is running on a Unix machine that contains the .ppt file, but the Unix machine doesn't know that .ppt maps to "application/vnd.ms-powerpoint", I still want the mail attachment's mime-type to go out as "application/vnd.ms-powerpoint". How can I set the mime type for files the Java mail system may not correctly identify. For example, I may want to set the mime-type of a .bat attachment as "text/plain".

Mon Feb 07 22:25:43 PST 2000
[Member not logged in]
Message msg = new MimeMessage(session);
msg.setFrom( aDefaultFromAddress );
InternetAddress[] address = {aToAddress};
msg.setRecipients(
Message.RecipientType.TO, address);
msg.setSubject( pSubject );
msg.setSentDate(new java.util.Date());
// create and fill the first message part
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText(pMessage);
// create the second message part
MimeBodyPart mbp2 = new MimeBodyPart();
// attach the file to the message
FileDataSource fds=
new FileDataSource(pFileName);
mbp2.setDataHandler(
new DataHandler(fds));
mbp2.setFileName(pFileName);
// create the Multipart
//and its parts to it
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
mp.addBodyPart(mbp2);
// add the Multipart to the message
msg.setContent(mp);
Transport.send(msg);



Wed Feb 09 01:08:08 PST 2000
[Member not logged in]
* Select a file to be attached as a part of mailing message. You can use standard file open dialog to choose the file. The following function will be called by action performed on a 'Attach' ( for ex) button...

void attachFile()
{

FileDialog file =
new FileDialog(this,"Select Attachment",FileDialog.LOAD);
file.show();
attachfile.setVisible(true);
String full= "" + file.getDirectory() + file.getFile();
attachfile.setText(full);
filename=attachfile.getText();
}
* filename is the fully qualified name of attachment to be sent. *This is part of code which actually does the sending part of the attachment, and these are few instances of classes which will be required
Transport tra = null;
MimeMessage msg = null;
Session session = null;
Multipart mp = new MimeMultipart();
==================
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText(content.getText());
Multipart mp = new MimeMultipart();
if (filename == null)
mp.addBodyPart(mbp1);
else
{
// create the second message part
MimeBodyPart mbp2 = new MimeBodyPart();
// attach the file to the message
FileDataSource fds=new FileDataSource(filename);
mbp2.setDataHandler(new DataHandler(fds));
mbp2.setFileName(filename);

// create the Multipart and its parts to it

mp.addBodyPart(mbp1);
mp.addBodyPart(mbp2);
}

// add the Multipart to the message
msg.setContent(mp);


//create complete address array

address = InternetAddress.parse(temp, false);

// get the smtp transport for the address
tra=session.getTransport(address[0]);
tra.addConnectionListener(new ConnectionHandler());

tra.addTransportListener(new TransportHandler());
tra.connect();
tra.send(msg,address);
================
Hope this will solve your problem. In case of difficulty, contact me on rajeev_kverma@hotmail.com




"THE INFORMATION PROVIDED IN THE JAVA DEVELOPER'S CONNECTION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR, AND NON-INFRINGEMENT.

THIS INFORMATION IS PROVIDED AT NO CHARGE. BY USE OF THE INFORMATION YOU AGREE THAT NEITHER SUN MICROSYSTEMS, INC. NOR ITS LICENSORS WILL BE LIABLE FOR ANY DAMAGES WHATSOEVER INCLUDING DIRECT, INDIRECT, INCIDENTAL, CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF SUN OR ITS LICENSORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES SO THE FOREGOING LIMITATION MAY NOT APPLY.

THIS INFORMATION COULD INCLUDE TECHNICAL INACCURACIES OR TYPOGRAPHICAL ERRORS. CHANGES ARE PERIODICALLY ADDED TO THE INFORMATION HEREIN. SUN MICROSYSTEMS, INC. MAY MAKE IMPROVEMENTS AND OTHER CHANGES IN THE PRODUCTS AND THE PROGRAMS DESCRIBED HEREIN AT ANY TIME WITHOUT NOTICE."

_______
1 As used on this web site, the terms "Java Virtual Machine" or "JVM" mean a Virtual Machine for the Java platform.


Print Button
[ This page was updated: 4-Apr-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Sun Microsystems, Inc.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.