Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

relative path

Status
Not open for further replies.

George221

MIS
Dec 2, 2005
50
US
I'm trying to attach a file to an email but are having trouble with the path to it.
What does the syntax look like for the .Setfilename property.

I tried copying the file in the root of the application directory and refering to it as .Setfilename("./myfile.txt") or just ("myfile.txt") but that didn't work. Any ideas.
Thanks.
 
You don't specify what email library you are using.

Tim
 
I wrote this a while ago ... see the "attach" method.


Code:
/**
*	Library name : Primrose - A Java Database Connection Pool.
*	Published by Ben Keeping, [URL unfurl="true"]http://primrose.org.uk[/URL] .
*	Copyright (C) primrose.org.uk
*
*	This library is free software; you can redistribute it and/or
*	modify it under the terms of the GNU Lesser General Public
*	License as published by the Free Software Foundation; either
*	version 2.1 of the License, or (at your option) any later version.
*
*	This library is distributed in the hope that it will be useful,
*	but WITHOUT ANY WARRANTY; without even the implied warranty of
*	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
*	Lesser General Public License for more details.
*
*	You should have received a copy of the GNU Lesser General Public
*	License along with this library; if not, write to the Free Software
*	Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/
package uk.org.primrose.web;

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import java.io.*;
import javax.activation.*;

/**
 * @author Ben Keeping
 *
 * Generic sendMail class, allows for sending emails with attachements.
 */
public class SendMail {
	static String mxServer;
	String toAddress, fromAddress;
	String subject, text;
	MimeBodyPart mbp = null;
	Multipart mp = new MimeMultipart();


	/**
	* Construct an email. <BR>
	* If the mxServer is unknown, then the static method SendMail.nslookup() can be called to retrieve the domain's mx server. <BR>
	* Attachments are optional. <BR>
	* @param String mxServer - The Mail eXchange server to send the mail to.
	* @param String toAddress - The recipient.
	* @param String fromAddress - The sender - can be anyting as long as looks like an email address - eg 'me@somewhere.com'.
	* @param String subject - The mail's subject.
	* @param String text - The body of the mail.
	*/
	public SendMail(String mxServer, String toAddress, String fromAddress, String subject, String text) {
		this.mxServer = mxServer;
		this.toAddress = toAddress;
		this.fromAddress = fromAddress;
		this.subject = subject;
		this.text = text;

	}

	/**
	* Add an attachment to the mail (from a file on disk).
	* @param File file - the File object to attach.
	*/
	public void attach(File file) {
		try {
			mbp = new MimeBodyPart();
			mbp.setFileName(file.getName());
			mbp.setDataHandler(new DataHandler(new FileDataSource(file)));
			mp.addBodyPart(mbp);
		} catch (MessagingException me) {
			me.printStackTrace();
		}
	}

	/**
	* Send a message using the contstructor properties.
	* If there is also an attachment to send, add it too.
	*/
	public void send() throws IOException {
		Properties props = System.getProperties();
		props.put("mail.smtp.host", mxServer);
		Session session = Session.getDefaultInstance(props, null);

		try {
			Message msg = new MimeMessage(session);
			msg.setFrom(new InternetAddress(fromAddress));
			msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddress, false));
			msg.setSubject(subject);
			msg.setHeader("X-Mailer", "JavaMail");

			// If there have been attachments (one or more), then set the text/body
			// as a MimeBodyPart, else set it on the Message. If this isn't done,
			// then either text or an attachment is sent - not both !
			if (mbp != null) {
				MimeBodyPart mbp2 = new MimeBodyPart();
				mbp2.setText(text);
				mp.addBodyPart(mbp2, 0);
				msg.setContent(mp);
			} else {
				msg.setContent(text, "text/html");
			}

			Transport.send(msg);
		} catch (AddressException ae) {
			ae.printStackTrace();
			throw new IOException("[SendMail] Address is invalid for mail " +ae.toString());
		} catch (MessagingException me) {
			me.printStackTrace();
			throw new IOException("[SendMail] Message send exception " +me.toString());
		}
	}

	/**
	* Given a domain name like 'hotmail.com', perform an OS nslookup call,
	* and loop it, looking for the word 'exchanger' in the line. On Linux and Windoze
	* the mx mail server is always the last word/token in the line, so set it as such.
	* This pays no attention to the preference of which mx server to use, but could (and should !)
	* be built in really. Still, never mind.
	* @param String domain - the domain to lookup.
	*/
	public static String nslookup(String domain) {
		String mailserver = null;
		try {
			Process p = Runtime.getRuntime().exec("nslookup -type=mx " +domain);
			BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));

			boolean gotMxLine = false;
			String line = null;
			String token = null;

			while ((line = br.readLine()) != null) {
				gotMxLine = false;
				//System.out.println(line);
				StringTokenizer st = new StringTokenizer(line);
				while (st.hasMoreTokens()) {
					token = st.nextToken();
					if (token.equals("exchanger")) {
						gotMxLine = true;
					}
					if (gotMxLine) {
						mailserver = token;
					}
				}

			}
		} catch (IOException ioe) {
			ioe.printStackTrace();
			return null;
		}

		System.out.println("Mail Server to use is :: " +mailserver);
		return mailserver;
	}

  /**
   * Method main.
   * @param args
   * Usuage :: <mxServer> <toAddress> <fromAddress> <subject> <text>
   */
	public static void main(String args[]) throws Exception  {
		if (args.length < 5) {
			System.out.println("Usuage :: <mxServer> <toAddress> <fromAddress> <subject> <text>");
			System.exit(1);
		}
		//BufferedReader br1 = new BufferedReader(new FileReader("C:/email_list_primrose_2.4.txt"));
		//String line1 = "";
		//while ((line1 = br1.readLine()) != null) {
		//	args[1] = line1;

			String text = "";
			// Read in the text for the body ...
			BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(args[4])));
			String line = "";
			//System.err.println("Getting body of email ...");
			while ((line = br.readLine()) != null) {
				text += line +"\n";
			}

			//String msgText = "";
			//        for (int i = 4; i < args.length; i++) {
			//	msgText += (" " +args[i]);
			//}

			new SendMail(args[0], args[1], args[2], args[3], text).send();
		//}


/*
if (args.length < 5) {
			System.out.println("Usuage :: <mxServer> <toAddress> <fromAddress> <subject> <text>");
			System.exit(1);
		}
		BufferedReader br1 = new BufferedReader(new FileReader("C:/java/primrose/email_list_2.4.6.txt"));
		String line1 = "";
		while ((line1 = br1.readLine()) != null) {

			System.err.println("Sending to : " +line1);

			args[1] = line1;

			String text = "";
			// Read in the text for the body ...
			BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(args[4])));
			String line = "";
			while ((line = br.readLine()) != null) {
				text += line +"\n";
			}

			//String msgText = "";
			//        for (int i = 4; i < args.length; i++) {
			//	msgText += (" " +args[i]);
			//}

			SendMail sm = new SendMail(args[0], args[1], args[2], args[3], text);
			sm.attach(new File("C:/java/primrose/web/downloads/primrose.jar"));
			sm.send();
		}

*/
	}
}

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
I do not want to pass the absolute path. I'm looking for the relative path.
I placed the attachement in the folder containing the first program being called and refered to it as "./myfile.txt"
but that didn't work. Why is my app not finding the file to attach?
 
The current working directory is not where your .class file which has the main() method in resides, it is where the programme is started from.

You can prove this by doing :

File f = new File(".");
System.out.println("CWD : " +f.toString());

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top