Sending attachment from servlet or jsp
Dear Friends,
I downloaded javamail api and I have seen the sendfile.java, which is used to send attachments. it is working fine. I can able to run that program from command prompt like this :=
c:>java sendfile [email protected] [email protected] mail.smtp.net c:/hello.java true
It is working fine from console (command prompt)
How can i execute that file on browser (i have to run as a servlet file or from jsp file).
please help me how can i pass the emailids, file etc., if i want to use this program as servlet file or as jsp program.
If anyone having idea, please share ur ideas.
your kind cooperation would be greatly appreciated.
Thanks in advance.
Looking forward to hearing from you.
Yours
Rajesh
==
program is like this (which is in javamail home ..demo directory
==
import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
* sendfile will create a multipart message with the second
* block of the message being the given file.<p>
* This demonstrates how to use the FileDataSource to send
* a file via mail.<p>
* usage: <code>java sendfile <i>to from smtp file true|false</i></code>
* where <i>to</i> and <i>from</i> are the destination and
* origin email addresses, respectively, and <i>smtp</i>
* is the hostname of the machine that has smtp server
* running. <i>file</i> is the file to send. The next parameter
* either turns on or turns off debugging during sending.
* @author Christopher Cotton
public class sendfile {
public static void main(String[] args) {
if (args.length != 5) {
System.out.println("usage: java sendfile <to> <from> <smtp> <file> true|false");
System.exit(1);
String to = args[0];
String from = args[1];
String host = args[2];
String filename = args[3];
boolean debug = Boolean.valueOf(args[4]).booleanValue();
String msgText1 = "Sending a file.\n";
String subject = "Sending a file";
// create some properties and get the default Session
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
Session session = Session.getDefaultInstance(props, null);
session.setDebug(debug);
try {
// create a message
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
// create and fill the first message part
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText(msgText1);
// 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(fds.getName());
// 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);
// set the Date: header
msg.setSentDate(new Date());
// send the message
Transport.send(msg);
} catch (MessagingException mex) {
mex.printStackTrace();
Exception ex = null;
if ((ex = mex.getNextException()) != null) {
ex.printStackTrace();
Hi,
your sendmail.jsp would look like that:
<%@ page import="java.util.*,java.io.*,javax.mail.*,javax.mail.internet.*,javax.activation.*" %>
<%
String to = request.getParameterValues("to")[0];
String from = request.getParameterValues("from")[0];
String host = request.getParameterValues("host")[0];
String filename = request.getParameterValues("filename")[0];
String msgText1 = "Sending a file.\n";
String subject = "Sending a file";
// create some properties and get the default Session
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
Session session = Session.getDefaultInstance(props, null);
session.setDebug(debug);
try {
// create a message
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
// create and fill the first message part
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText(msgText1);
// 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(fds.getName());
// 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);
// set the Date: header
msg.setSentDate(new Date());
// send the message
Transport.send(msg);
} catch (MessagingException mex) {
mex.printStackTrace();
Exception ex = null;
if ((ex = mex.getNextException()) != null) {
ex.printStackTrace();
%>
which you can call as: sendmail.jsp?to=...&from=...&host=...&filename=...
so you may need to create a HTML file containing the necessary form.
Similar Messages
-
How to send the values from servlet to jsp
hi folks,
I need to send a lot of values from servlet to jsp so that i can display the values in jsp. Any sollution for this. Its very urgent.
Thanks in advanceHi lieo,
Can u send me the sample code for that.
Thank q -
Pass data from servlet to jsp using sendRedirect
Hi,
I am passing data from servlet to jsp using forward method of request dispatcher but as it doesn't change the url it is creating problems. When ever user refreshes the screen(browser refresh) it's re-loading both servlet and jsp, which i don't want to happen. I want only the jsp to be reloaded.
Can I pass data from servlet to jsp using sendRedirect in this case. I also want to pass some values from servlet to jsp but without using query string. I want to set some attributes and send to jsp just like we do for forward method of request dispatcher.
Is there any way i can send data using attributes(without using query string) using sendRedirect? Please let me knowsendRedirect is meant as a true redirect. meaning
you can use it to redirect to urls not in your
context....with forward you couldn't pass information
to jsps/servlets outside your own context.Actually, you can:
getServletContext().getContext("/other").getRequestDispatcher("/path/to/servlet").forward(request, response)I think the issue here is that the OP would like to have RequestDispatcher.forward() also update the address in the client's browser. That's not possible, AFAIK. By the time the request is forwarded, the browser has already determined the URL of the servlet, and the only I know of way to have the browser change the URL to the forwarded Servlet/JSP is to send a Location: header (i.e. sendRedirect()). Remember that server-side dispatching is transparent to the client. Maybe there's some tricky stuff you can do with JavaScript to change the address in the address bar without reloading the page?
Brian -
How to send mail from servlets
m having troubles sending mail from servlets...
how do you use the SimpleMailUser object needed in the session?
a sample code on this would be of great help, thanks!<html>
<body bgcolor="white">
<font size=5 color="black">
<%@ page import="javax.servlet.http.HttpUtils" %>
<%@ page import="java.util.*" %>
<%@ page import = "java.sql.*" %>
<%@ page import = "java.io.*" %>
<%@ page import= "sun.net.smtp.SmtpClient" %>
<%
String from,to,subject,msgbody,serverName;
try
from = request.getParameterValues("from")[0];
to = request.getParameterValues("to")[0];
subject = request.getParameterValues("subject")[0];
msgbody = request.getParameterValues("msgbody")[0];
serverName = request.getParameterValues("server")[0];
catch (Exception e) // Generally Speaking, an Error getting one of these
// Values means that it wasnt passed in; inform the user
out.println("You must call this JSP from this ");
out.println("<A href=\"FormMail.htm\"> form</A>.<BR>");
out.flush();return;
%>
Hold On A Moment while I try to Send Your Mail... <BR>
<%
out.flush();
// Here are the real guts of the mail sending
try
sun.net.smtp.SmtpClient sm = new sun.net.smtp.SmtpClient(serverName);
sm.from(from);
sm.to(to);
PrintStream msg = sm.startMessage();
msg.println("To: "); // Note dont use + for Performance
msg.println(to);
msg.println("Subject: ");
msg.println(subject);
msg.println();
msg.println(msgbody);
msg.println("==============");
msg.print("This mail brought to you by JSP MAIL..from a user at IP ");
msg.println(request.getRemoteHost());
sm.closeServer();
out.println("Your Mail Has Been Sent!");
catch (Exception e)
out.println("The mail couldn't be sent, probably because the mailhost wasnt set correctly.<BR> ");
out.println("The error message I am getting is: ");
out.println(e.getMessage());
%>
<BR>
<BR>
Click here to send another! -
I can't use thunderbird 31.2.0 to send attachement from a pdf file with Acrobat PRO XI
I can't use thunderbird 31.2.0 (Mozilla) to send attachement from a pdf file with Acrobat PRO XI. Each time, Acrobat replies (in french) : "il n'y a pas de client pour la messagerie par défaut". Thunderbird is indicated as "by default" in the list of programs of Windows.
Even if I type my e-mail address, etc. in the account of Acrobat, it doesn't change. Each time, I have to record a PDF file in a folder and return to Thunderbird to send it as attached. It is a too long process, compared with Windows XP with Acrobat Reader or Acrobat 5, I had before.
Would you please help me to explain the process. My OS is Windows 8.1.
Thank youThank you for your answer.
What i want to do : to send PDF files as attached documents in a message
generated by thunderbird by my e-mail address [email protected] or
another one I have.
When I introduce my e-mail address under Edit-Preferences-Email
Accounts, Acrobat ask the e-mail account, the password, the IMAP for
ingoing message (and I use POP) and SMTP for outgoing messages. Even I
introduce all the datas, it doesn't change, Acrobat is unable to send
the message. And the process is not convenient, because I need all my
outgoing messages be documented inside Thunderbird.
So, I repeat my request : how can I use thenderbird as program by
default from Acrobat or any other software ?
Thank you for your next message.
Jean-Luc Rongé
Le 21-10-14 14:24, ANAND8502 a écrit :
>
I can't use thunderbird 31.2.0 to send attachement from a pdf
file with Acrobat PRO XI
created by ANAND8502 <https://forums.adobe.com/people/ANAND8502> in
/Acrobat Installation & Update Issues/ - View the full discussion
<https://forums.adobe.com/message/6850947#6850947> -
Parameter passing from servlet to jsp page
Hi
I m facing problem of parameter passing from servlet to jsp ..
plz help me...
I m using as ...
in servlet code I m using ...
request.setAttribute("string",parameter);
and in jsp..
request.getParameter("string");
regard's
JAI KUMARHi Jaykumar
You should use
<%= request.getAttribute("sting") %> or
${string}
in your jsp. I think you are trying to retrive the parameter instead of attribute.
Thanks -
How to send a message from Servlet to JSP
Dear all,
I have JSP, with JavaScript (AJAX). If the user click on the button, the text will be sent to a Servlet parsed by doGet() and the user get a response to his input, without reloading a page.
How can I send a message to the users (JSP) from Servlet, if he didn't clicked any button and to other visitor of the page also? Is it possible? I think like a chat, the server sends a message to all users who are subscribed.
I don't know, what should I get from user, maybe session, that I could send him personal or common messages in his textarea. I should also invoke some JavaScript function to update his page. I have met some chats, you don't do nothing and get messages. It is also without a JavaScript timer, which invokes doGet() method. Asynchronous, only when there is a message.
Please help me with a problem.
Thanks in advance.Hai ,
You can send any message through response.sendRedirect();
here is the coding try it
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SimpleCounter extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
String username="java";
res.sendRedirect("http://localhost:8080/yourprojectname/jspfile.jsp?username="+username);
} -
Error message from servlet to jsp
Hi again,
I have servlet and check error on this servlet then i would like
to send error message to jsp page.Every error message will send to
same JSP page.So JSP must receive message from Servlet.Can i do this?
Please give me details and some sourcecode.I will appreciate for your helps.you could do something like this..
request.setAttribute("error", stringErrormessage);
Then in the jsp just do
<%= request.getAttribute("error") %>
That will print an errormessage.
Basically, by setting anything on the request and then redirecting to that page you cn display it...
//Johan -
Email with attachment from servlet
Hi. We're using Java 1.4.2_12 and need to send emails with an image file attachment from a servlet. The JavaMail API looks interesting but wasn't sure if it works with our (ancient) version of Java. Your help is much appreciated. Thanks.
Edited by: curios_Lee on Jan 16, 2009 8:38 AMI didn't find it. Generally people who write Java APIs like that will document restrictions (like "Requires Java 5 or later") if they exist. You won't generally find "Works will all versions of Java" in the documentation because that's just a basic assumption of Java.
-
How do I lookup an EJB 3.0 Session bean from servlet or JSP?
Does anyone knows how can I invoke an EJB from a servlet or JSP ?
I deployed a simple EJB on a Oracle Application Server 10g release 10.1.3 and I'm working with JDeveloper 10.1.3. I deployed the files via JDeveloper, and I didn´t specify any orion-ejb-jar.xml or ejb-jar.xml file
After deployment, the orion-ejb-jar.xml look like this in the server:
<?xml version="1.0" encoding="utf-8"?>
<orion-ejb-jar xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://xmlns.oracle.com/oracleas/schema/orion-ejb-jar-10_0.xsd" deployment-version="10.1.3.0.0" deployment-time="10b49516c8f" schema-major-version="10" schema-minor-version="0" >
<enterprise-beans>
<session-deployment name="HolaMundoEJB" location="HolaMundoEJB" local-location="HolaMundoEJB_HolaMundoEJBLocal" local-wrapper-name="HolaMundoEJBLocal_StatelessSessionBeanWrapper6" remote-wrapper-name="HolaMundoEJB_StatelessSessionBeanWrapper7" persistence-filename="HolaMundoEJB.home_default_group_1">
</session-deployment>
</enterprise-beans>
<assembly-descriptor>
<default-method-access>
<security-role-mapping name="<default-ejb-caller-role>" impliesAll="true" />
</default-method-access>
</assembly-descriptor>
</orion-ejb-jar>
I'm trying to invoke the ejb in a servlet by doing the following:
public void doGet(HttpServletRequest request, ....
Context context = new InitialContext();
HolaMundoEJB helloWorld =
(HolaMundoEJB)context.lookup("java:com/env/ejb/HolaMundoEJB");
String respuesta = helloWorld.sayHello("David");
When i invoke the servlet I catch a NamingException whose message says something
like this ....java:com/env/ejb/HolaMundoEJB not found in webLlamaEJB
I tried different paths for the lookup but nothing....
Can anyone help me with this topic? Thank you.Please try the following code:
HelloEJBBean.java:
@Stateless(name="Hello")
@Remote(value={Hello.class})
public class HelloEJBBean implements Hello { ... }
hello.jsp:
Context ctx = new InitialContext();
Hello h = (Hello)ctx.lookup("ejb/Hello");
web.xml:
<ejb-ref>
<ejb-ref-name>ejb/Hello</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<remote>fi.kronodoc.test.model.Hello</remote>
</ejb-ref>
i think you should also define jndi mappings for the references in orion-ejb-jar.xml and orion-web.xml but for some reason it seems to be working also without these. -
Sending Attachment from SAP ECC to a Thirdy Party system
All,
Any inputs on how to send an attachment from SAP ECC to an external system(3rd party). I think this has something to do with creation of RFC destination of connection type "G". But then how can i use this RFC destination in a program?
Correct Answers will be rewarded suitably.
ThanksHi Narasimha,
We can do this with the help of PI. Please find the below link.
http://www.sdn.sap.com/irj/scn/go/portal/prtroot/docs/library/uuid/404ee507-3fbc-2e10-00bc-be90ab28d036?QuickLink=index&overridelayout=true&52239687237174
Its from SAP PI to any other system.
Check this link too.. Proxy with Attachments.
Regards,
Siva -
Creating files from servlets or jsp
The issue that I have is this
I've been working with eclipse, netbeans, tomcat, glassfish, servlets and jsps.
I have a little servlet/jsp web application that create few files from the servlet. Those files I need to make them visible to the browser because they are the end result of the servlets/jsp work.
When I run the server from netbeans/eclipse they deploy the war file into tomcat/glassfish server and run the app.
So far there is no problem here, just that.. the files created with the app are created into the project folder.
If I manually run the server, those files are created in the folder from I started the server, so what I did is get into the deployed/unpacked war and from there start the server.
Only that way I could make those files visibles to download.
Is there a better way to do this? (of course, it must be, but I don't know how).
What I want is, deploy the web-app and make the app create those files at the same folder of the web-app to allow those file could be downloaded, no matter from where or how the server is started.
In the near future I need to install few web-apps like this at the same server, so I can't still starting the server from the web-app folder (as I did it until now).
I read about the request.getContextPath(); but it return no the real address just the context address (something like "/my_app"), so when I use that address to create a file, what I get is something lik "/my_app/myFile.txt".
I hope you can give some advices of how to solve my issue.
Thanks in advance830896 wrote:
Right now I know the absolute path to the tomcat/glassfish where the web-app is deployed, so I can use that address, but in the future that web-app could be deployed in another server and I can't know what address does it have.
I wonder if there exists a way to know the current absolute address of the web-app, or a way to create, "%this-web-app-absolute-addres%/someDir/myNewFile.txt"No, you're solving the wrong problem. Don't store files you create in the context of the web application, or even in the context of the application server. Store them somewhere else entirely. Then the person who configures the web application just has to set up the name of the directory where they are stored as a variable for your application. -
Returning ResultSet from servlet to jsp - java.lang.NullPointerException
Hey all, i've been stuck on this for too long now...just trying to return a ResultSet from a servlet to jsp page.
Had a bunch of problems earlier...which i think were fixed but...now i get a "java.lang.NullPointerException" in my jsp page when i try to get elements from the ResultSet object.
Here is the latest version of my code:
Servlet:
String QueryStr="select ProdName from products";
Statement stmt=conn.createStatement();
rs=stmt.executeQuery(QueryStr); //get resultset
sbean.setInventory(rs); //set ResultSet in bean
req.getSession(true).setAttribute("s_resbean",sbean); //create session/request variable, set to bean
Bean:
package beans;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import javax.sql.*;
public class SearchBean extends HttpServlet{
private int searchFlag=0;
private ResultSet inventory;
public SearchBean(){
public int getSearchFlag(){
return searchFlag;
public ResultSet getInventory(){
return inventory;
public void setInventory(ResultSet rs){
this.inventory=rs;
public void setSearchFlag(){
this.searchFlag=1;
jsp:
<%@ page language="java" import="java.lang.*,java.sql.*,javax.sql.*,PopLists.PopInvLists,beans.SearchBean"%>
<jsp:useBean scope="session" id="s_resbean" class="beans.SearchBean" />
<% ResultSet categories=PopInvLists.getCat();
ResultSet manuf=PopInvLists.getManuf();
ResultSet supplier=PopInvLists.getSupplier();
ResultSet cars=PopInvLists.getCars();
ResultSet search=(ResultSet)request.getAttribute("s_resbean");
%>
<% while(search.next()){
String pname=search.getString("ProdName");
%>
It craps out when i try to loop through the "search" ResultSet.
I can loop through the rest of the ResultSets no problem....just this one doesn't work because it's set in a servlet, not a simple java class.
Just to clarify, i am populating some dropdown lists on entry to the screen, which the user will use to perform a search. Once the search btn is clicked, the servlet is called, gets the request info for the search, performs search, and returns the resultset to the original screen. I want to eventually display the result under the search criteria.
Someone....Please Please please tell me how to get this working...it should be very simple, but i just can't get it to work.
Thanks in advance,
Adityareq.getSession(true).setAttribute("s_resbean",sbean); //create session/request variable, set to beanHere you add an attribute to the session.
ResultSet search=(ResultSet)request.getAttribute("s_resbean");Here you try to get the attribute from the request. Naturally it isn't there because you added it to the session, not the request. Despite your comment in the first line of code, a session is not a request. And vice versa. -
How to send object arraylist from servlet to jsp and display using jstl
Hi All....
I have a simple application and problem with it.
Once user logged in to system the user will redirect to LoginServlet.java controller.
Then in LoginServlet I want to redirect user to another page called book_details.jsp.
this is my login servlet.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
ArrayList<BankAccountDTO> account_list = new ArrayList();
ResultSet resultSet = null;
LowFairAirDB airDB = null;
try{
airDB = new LowFairAirDB();
String query = "SELECT account_id, type, description, balance, credit_line, begin_balance, begin_balance_time_stamp FROM bank_account";
airDB.sqlSelect(query);
resultSet = airDB.getResultSet();
while(resultSet.next()){
account_list.add(new BankAccountDTO(resultSet.getInt(1),
resultSet.getInt(4),
resultSet.getInt(5),
resultSet.getInt(6),
resultSet.getString(2),
resultSet.getString(3),
resultSet.getString(7)));
}catch(Exception ex){
}finally{
try{resultSet.close();}catch(Exception ex){}
airDB.sqlClose();
}I set bank account values to BankAccountDTO.java objects and add them to the arrayList.
Next I want to send this objects arrayList to books_details.jsp and wanna display each objects values using JSTL.
I still finding a way to go through this.
1. Can anyone say how can I do it?
2. Is there any other method to do the same thing without using JSTL?
thanks in advance,
Dil.Naishe wrote:
In your servlet,
request.setAttribute("account_list", account_list);
requestDispatcher.findForward("/your/display/jsp");
Good. I would only follow the Java naming conventions. E.g. accountList or accounts instead of the ugly PHP/C conventions.
In the JSP,
lst = (List< BankAccountDTO >)request.setAttribute("account_list");
for(BankAccountDTO b: lst){
populate your HTML tags or whatever
Wrong. 1) You need getAttribute() and 2) you should not use scriptlets. Use JSTL c:forEach, e.g.<table>
<c:forEach items="${accounts}" var="account">
<tr>
<td>${account.id}</td>
<td>${account.type}</td>
<td>${account.description}</td>
</tr>
</c:forEach>
</table>To the topicstarter: for future JSP/JSTL related questions please use JSP/JSTL forum.
Here it is: [http://forums.sun.com/forum.jspa?forumID=45]. -
Session Rules from Servlet to JSP
I'm getting a null pointer exception from the else statement in the JSP below when I check to see if a user has been authenticated by a servlet.
Are there any problems with the else statement to cause an exception?
<% /**Verify Authenticationt*/
HttpSession mysession = request.getSession();
String loginUrl = "/hr/servlet/SessionLoginServlet";
if (mysession==null)
response.sendRedirect(loginUrl);
else { //below code causing null pointer exception
String loggedIn = (String) mysession.getAttribute("loggedIn");
if (!loggedIn.equals("true"))
response.sendRedirect(loginUrl);
%>
The Servlet's doPost:
public void doPost(HttpServletRequest request, HttpServletResponse
response)throws ServletException, IOException {
String userName = request.getParameter("userName");
String password = request.getParameter("password");
if (login(userName, password, response)) {
//send cookie to the browser
HttpSession session = request.getSession(true);
session.setAttribute("loggedIn", new String("true"));
response.sendRedirect("/hr/jsp/PAStart.jsp");
else {
sendLoginForm(response, true);
}Unfortunately, no. You'll need to say:
if (loggedIn != null || !loggedIn.equals("true"))
It's how the equals() works for String objects. You need two objects to check equality.
Maybe you are looking for
-
hi
-
HT4528 how come my iphone wont finish downloading songs?
Ive continually tried downloading songs from the itunes store to my phone but the download stops half way and just keeps restarting. Why is this happening? why wont the song just download?
-
Sapscript symbol for a certain line containing variable characters
Hi, Can you tell me a symbol in sapscript that tells us the size of a certain line ? Meaning that if I choose font Times new roman with size 10 and I have 30 characters, then the symbol can tell me how wide my line of 30 characters is. When I increas
-
MacBook Pro C2D Wireless issues after 10.4.10 - issue pin pointed !
I have a MacBook Pro C2D which has started to do random disconnects from my WLAN. I am running the latest Tiger 10.4.10 No matter if I use the network connection actively by surfing, chatting, listening to netradio, downloading or if it is just idle,
-
Is it true that it is not advisable to run OS X client on an xServe? It would be only used as a webserver and don't really need the gui tools.