Check the [url=http://java.sun.com/products/javamail/]JavaMail API[/url].
It's relatively easy, here is a basic example:// Get session.
Properties properties = new Properties();
properties.put("mail.smtp.host", "smtp.example.com");
Session session = Session.getDefaultInstance(properties, null);
try {
// Prepare message.
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from@example.com"));
message.setRecipient(Message.RecipientType.TO, new InternetAddress("recipient@example.com"));
message.setSubject("subject");
message.setContent("message", "text/plain");
// Send message.
Transport.send(message);
} catch (MessagingException e) {
// Handle exception.
e.printStackTrace();
}
[nobr]here is the complete , working code with attachment:
package myClasses;
public class EMailBean {
private String smtp,username,password,from,to,cc,bcc,subject,body,attachments;
/*setter*/
public void setSmtp(String str){this.smtp=str;}
public void setUsername(String str){this.username=str;}
public void setPassword(String str){this.password=str;}
public void setFrom(String str){this.from=str;}
public void setTo(String str){this.to=str;}
public void setCc(String str){this.cc=str;}
public void setBcc(String str){this.bcc=str;}
public void setSubject(String str){this.subject=str;}
public void setBody(String str){this.body=str;}
public void setAttachments(String str){this.attachments=str;}
/*getter*/
public String getSmtp( ){return this.smtp;}
public String getUsername( ){return this.username;}
public String getPassword( ){return this.password;}
public String getFrom( ){return this.from;}
public String getTo( ){return this.to;}
public String getCc( ){return this.cc;}
public String getBcc( ){return this.bcc;}
public String getSubject( ){return this.subject;}
public String getBody( ){return this.body;}
public String getAttachments( ){return this.attachments;}
}
package myClasses;
import java.util.Properties;
import java.util.Date;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.*;
public class SendMailBean {
public String send(EMailBean mail) {
String result = "<BR><BR><BR><BR><BR><BR><BR>";
Properties props = System.getProperties();
props.put("mail.smtp.host", mail.getSmtp());
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props, null);
session.setDebug(true);
try {
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(mail.getFrom()));
msg.addRecipient(Message.RecipientType.TO,new InternetAddress(mail.getTo()));
msg.setSubject(mail.getSubject());
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText(mail.getBody());
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(mail.getAttachments());
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(source.getName());
multipart.addBodyPart(messageBodyPart);
msg.setContent(multipart);
msg.setSentDate(new Date());
Transport t = session.getTransport("smtp");
try {
t.connect(mail.getUsername(), mail.getPassword());
t.sendMessage(msg, msg.getAllRecipients());
} finally {
t.close();
}
result = result + "<FONT SIZE=4 COLOR=\"blue\"><B>Success!</B>"+"<FONT SIZE=4 COLOR=\"black\"> "+"<HR><FONT color=green><B>Mail was successfully sent to </B></FONT>: "+mail.getTo()+"<BR>";
if (!("".equals(mail.getCc())))
result = result +"<FONT color=green><B>CCed To </B></FONT>: "+mail.getCc()+"<BR>";
if (!("".equals(mail.getBcc())))
result = result +"<FONT color=green><B>BCCed To </B></FONT>: "+mail.getBcc() ;
result = result+"<BR><HR>";
} catch (MessagingException mex) {
result = result + "<FONT SIZE=4 COLOR=\"blue\"> <B>Error : </B><BR><HR> "+"<FONT SIZE=3 COLOR=\"black\">"+mex.toString()+"<BR><HR>";
} catch (Exception e) {
result = result + "<FONT SIZE=4 COLOR=\"blue\"> <B>Error : </B><BR><HR> "+"<FONT SIZE=3 COLOR=\"black\">"+e.toString()+"<BR><HR>";
e.printStackTrace();
}
finally {
return result;
}
}
}
/////////////// index.jsp///////////////////////
[code]
<HTML>
<HEAD>
<TITLE>Sending Mail using Java Mail API</TITLE>
</HEAD>
<SCRIPT LANGUAGE="JavaScript1.1">
function submission1() {
if(document.forms[0].from.value =="" ||
document.forms[0].to.value =="" ||
document.forms[0].smtp.value =="") {
alert("Host, From and To fields are mandatory.");
return;
}
document.forms[0].action = "SendMail.jsp";
document.forms[0].submit();
}
</SCRIPT>
<CENTER>
<TABLE BGCOLOR=black WIDTH=100% CELLPADDING="1">
<TR><TD bgcolor="#FFFFFF">
<CENTER><B><FONT SIZE=3>Send Mail Page</TD></TR>
</TABLE>
<TABLE BORDER=0 >
<TR>
<TD>
<FORM METHOD=POST action="SendMail.jsp">
<TABLE BORDER=0 CELLPADDING=4>
<TR>
<TD ALIGN=RIGHT width="124"><b>Mail Server Host</b></TD>
<TD ALIGN=LEFT width="298">
<INPUT TYPE="text" NAME="smtp" SIZE=20 value="smtp.gmail.com" >
</TD>
</TR>
<TR>
<TD ALIGN=RIGHT width="124" height="31"><b>Username</b></TD>
<TD ALIGN=LEFT width="298" height="31">
<INPUT TYPE="text" NAME="username" SIZE=20 ></TD>
</TR>
<TR>
<TD ALIGN=RIGHT width="124"><b>Password</b></TD>
<TD ALIGN=LEFT width="298">
<INPUT TYPE="password" NAME="password" SIZE=20 ></TD>
</TR>
<TR>
<TD ALIGN=RIGHT width="124"><b>From</b></TD>
<TD ALIGN=LEFT width="298">
<INPUT SIZE=20 MAXLENGTH=60 NAME="from">
</TD>
</TR>
<TR>
<TD ALIGN=RIGHT width="124"><b>To</b></TD>
<TD ALIGN=LEFT width="298">
<INPUT SIZE=60 MAXLENGTH=200 NAME="to"></TD>
</TR>
<TR>
<TD ALIGN=RIGHT width="124"><b>CC</b></TD>
<TD ALIGN=LEFT width="298">
<INPUT SIZE=60 MAXLENGTH=200 NAME="cc"></TD>
</TR>
<TR>
<TD ALIGN=RIGHT width="124"><b>BCC</b></TD>
<TD ALIGN=LEFT width="298">
<INPUT SIZE=60 MAXLENGTH=200 NAME="bcc"></TD>
</TR>
<TR>
<TD ALIGN=RIGHT width="124"><b>Attachments</b></TD>
<TD ALIGN=LEFT width="298">
<input type="file" name="attachments" size="20"></TD>
</TR>
<TR>
<TD ALIGN=RIGHT width="124"><b>Subject</b></TD>
<TD ALIGN=LEFT width="298">
<INPUT SIZE=60 MAXLENGTH=100 NAME="subject" value="hi"></TD>
</TR>
</TABLE>
<p align="left">
<b>Message</b><br>
<TEXTAREA NAME="body" ROWS=7 COLS=66 SIZE=2000 WRAP=HARD>hihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihi</TEXTAREA>
<CENTER>
<INPUT TYPE=BUTTON VALUE=" Send " onClick="submission1();">
<br>
</CENTER>
</FORM>
</TD>
</TR>
</TABLE>
</CENTER>
</BODY>
</HTML>
///////////sendMail.jsp////////////
<%@ page contentType="text/html;charset=WINDOWS-1252"%>
<HTML>
<HEAD>
<TITLE>Send Email</TITLE>
</HEAD>
<CENTER>
<BR>
<%@ page import="myClasses.*"%>
<jsp:useBean id="sendMail" class="myClasses.SendMailBean" scope="page" />
<jsp:useBean id="email" class="myClasses.EMailBean" scope="page" />
<jsp:setProperty name="email" property="*"/>
<%
String result=sendMail.send(email);
%>
<%=result%>
<FONT SIZE=3 COLOR="blue">
<A HREF="index.jsp">Compose Mail</A>
</CENTER>
</BODY>
</HTML>
[/nobr]
@BaluSC
i've tried myself with all the possible code n facin problem. i'm not brainlessly copy pasting codes. if that was the case i wudnt have done my project on myself. dont comment on others like that. u may be genius but veryone may not be.... i'm a beginner n learning stufff...... i agree that u have posted 3000+posts n u know things. i want to stop here n dont wanna blame u...... thanks for ur support.....
BlausC,,, u always embarrass new users who asking about something and dont know the clear picture of the subject, so plz plz plz if u cant help them just just just dont post any thing like Search in google , read the API and so on...
this form is to help them ok ?
i provided him a code and this code is working and may clearfy the whole picture for him,, i hope u got what i meant.....
Help them or just dont try to increas the number of ur posts with useless and negative posts...
thank u very much
@Mohammed
Thanks a lot for ur support pal.... i'm still working on that code.... once i finish my project i'll provide u a link so that u can visit it. Prior to ur suggestion i had placed both .jar files in WEB-INF. i'll complete it pal..... thanks for ur valuable suggestions and support :)
With regards,
Kiran
> u need the followings jar files to be placed in lib
> folder within WEB-INF
> 1.activation.jar
> 2.mail.jar
>
> u can google for them
> good luck
Eng.Mohammed, the code you posted was good but this advice is not so good.
Quite often the application server will already include these jar files. If it does,
and if you put different versions in your WEB-INF/lib folder, then you can get
strange and confusing errors occurring.
Better advice would be to put those jar files in WEB-INF/lib only if they are
really needed. Try the application without them first.
DrClap thank u very much...
i knew that what u said preferable , but i tried my code without these JARs and it did't work unless i put them , this is the first point.
the second pint is that i think it is better to put these jars in the WEB-INF folder because the application may be traverse between many servers may be Tomcat, Sun App server , BEA,,,,, and so on . so the best practice is to include them in the WEB-Inf/Lib...
thats all
thanks for ur replay.
:)
@Mohammed
hiiiii dude..... i'm back with a prob again..... my proj is to demonstrated in a lan.... i'm not able to send mails through proxy..... i've tried a lot but not able to get it done..... the code is workin fine for a stand alone pal.... can u help me out? thanks in advance...
with regards,
Kiran
hi kiranbedre
>hiiiii dude
i dont know if dude is for me or what : ) : )
first which OS do do u use? if it is windwos XP sp2 , just disable the windows firewall ,,,,,
if u use any othe firewalls like kasperskey or what ever , close them,,,
if this doesnt work , replay me here
good luck
:)
yaa pal..... dude was for u itself... :P anywayz pal i'm using WIN xp sp2... even if the firewall is disabled and also there r no other firewalls... i'm unable to connect smtp... actually i'm tryin this in college where they use CYBEROAM.... i hope u know abt that....
hope u can help me out...
thanks yaa
@OP
What kind of proxy ?
Is it where you are using a server for sending mails via SMTP(operated on PORT 25)...If so,it does requires SMTP authentication
which you can do it by using the example code snippet provided in the below link.
http://www.example-code.com/java/java-smtp-authentication.asp
and If it is a Http Proxy() i don't think it has to do something with SMTP.
and a small advice I'm sorry to say this but your attitude was very wrong to what my fellow poster BALUS had adviced.I understand you might be a newbie and you might require real help but he had a point there where you can very well either learn javamail and activation api which are very nessary for any JAVA EE devoloper.If it was all about getting a quick solution you can very well google it and get a code after trying it out if you had a specific problem people here can certainly help you and
i'm sure Mr.Mohammed is no god even he might have either used some source / book / api documentation to provide the code.if he hadn't i'm sure he could be one among who devoloped activation & javamail api.
I would have been impressed if you could have asked My fellow poster Mr.Mohammed the logic behind the code where he had used very few comments and for a newbie understanding logic behind it would certainly be something similar to learning "Tibetian".
http://www.google.com/search?hl=en&rls=com.microsoft%3Aen-us%3AIE-SearchBox&rlz=1I7GFRC&q=sending+mail+java+JSP
therefore i'd like to conclude my discurssion stating whenever you find sometime sit on Activation & javamail apis and analyse different cases.
Just as an example what Mr.Mohammed has tried was making use of SMTP where it is very insecure way of your emails.you might very well send emails using an IMAP store etc & etc.
I'm sure this would do a world of good to you and to the forums where you'd well be in a position to solve problems which are more specfic.
just as an example you'd find thousands of issues at
http://forum.java.sun.com/forum.jspa?forumID=43 which are specific to javamail
Hope this advice doesn't hurt :)
REGARDS,
RaHuL
thanks for dude :)
yes i knew it , and u have to ask the internet providers in ur unversity about if they block any SMPT call or not ? they may block any outside connections for securty reasons.... this is one posibility...
the second is that u dont provide the correct SMTP ,, which one do u use ?
i used Gmail SMTP in my code and it works fine, and i dont know which code u used ...
good luck