Use Javamail and Ristretto
Hello, I'm using Javamail Api to do some functions, but to do something I need I have to use Ristretto Api. The problem is that I want to cast javax.mail.Message to Ristretto Message, but I don't get. It's possible do that?
I receive this error: "java.lang.ClassCastException : com.sun.mail.imap.IMAPMessage cannot be cast to org.columba.ristretto.message.Message"
I have done some tests and I have get a temporal solution. I have seen that Ristretto take a File to create the Message, and I will do that.
File emlFile = new File("C:/"+mensaje.getSubject()+".eml");
FileOutputStream out = new FileOutputStream(emlFile);
mensaje.writeTo(out);
Message message = MessageParser.parse(new FileSource(emlFile)); //Message is a Ristretto Message, not javax.mailMessageSomeone knows a beter solution after show this code. I would want to the same without create a File in the disc.
Thanks
Similar Messages
-
Problems using JavaMail and activation with Java 1.6
Hi,
I have developed an application with a SOAP architecture using Axis. Everything worked fine until I upgrade the JRE version from 1.5 to 1.6. Since then a "javax.activation.UnsupportedDataTypeException: no object DCH for MIME type multipart/related; type="text/xml" " exception is thrown every time I try to connect to the webservices.
Debugging the code I've found that the problem is a null value in the "dch" attribute of the ObjectDataContentHandler object returned by the getInputStream method in the DataHandler class.
When I launch the application using JRE 1.5 this attribute value is "text_plain" and everthing woks ok but when I launch it with JRE 1.6 the attribute has a wonderful "null" value...
Anybody knows what could be the reason for that "null" value?
I've looking for this problem in diferent forums and I believe that could be some kind of incompatibility between the activation version provided with the JRE 1.6 and the JavaMail 1.4 version but I'm not sure.
Thanks in advance!My application also stopped working and sadly is a production application (is in a production environment and production depends heavily on it since it contains Standard Operation Procedures documents).
I've tried so far uninstalling jre 1.6 from server, opening the jnlp with jre 1.5.13 and nothing yet. the curious thing is that the jre 1.6 update took place some time ago and today I'm getting the error. Not sure i the server went down recently which might explain some of it.
Here's my error:
java.lang.reflect.InvocationTargetException
at sun.reflect.GeneratedConstructorAccessor4.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at org.apache.axis.Message.setup(Message.java:352)
at org.apache.axis.Message.<init>(Message.java:235)
at org.apache.axis.transport.http.HTTPSender.readFromSocket(HTTPSender.java:779)
at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:144)
at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)
at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118)
at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83)
at org.apache.axis.client.AxisClient.invoke(AxisClient.java:165)
at org.apache.axis.client.Call.invokeEngine(Call.java:2784)
at org.apache.axis.client.Call.invoke(Call.java:2767)
at org.apache.axis.client.Call.invoke(Call.java:2443)
at org.apache.axis.client.Call.invoke(Call.java:2366)
at org.apache.axis.client.Call.invoke(Call.java:1812)
at com.bluecubs.xinco.client.XincoExplorer.doDataWizard(XincoExplorer.java:2788)
at com.bluecubs.xinco.client.XincoExplorer$8.mousePressed(XincoExplorer.java:1437)
at java.awt.AWTEventMulticaster.mousePressed(AWTEventMulticaster.java:263)
at java.awt.Component.processMouseEvent(Component.java:6035)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
at java.awt.Component.processEvent(Component.java:5803)
at java.awt.Container.processEvent(Container.java:2058)
at java.awt.Component.dispatchEventImpl(Component.java:4410)
at java.awt.Container.dispatchEventImpl(Container.java:2116)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3983)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
at java.awt.Container.dispatchEventImpl(Container.java:2102)
at java.awt.Window.dispatchEventImpl(Window.java:2429)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
Caused by: Error reading data stream: Error in MIME data stream, start boundary not found, expected: ------=_Part_5_13931643.1192823865125
at org.apache.axis.attachments.MultiPartRelatedInputStream.<init>(MultiPartRelatedInputStream.java:339)
at org.apache.axis.attachments.AttachmentsImpl.<init>(AttachmentsImpl.java:119)
... 39 more
AxisFault
faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.userException
faultSubcode:
faultString: java.lang.RuntimeException
faultActor:
faultNode:
faultDetail:
{http://xml.apache.org/axis/}stackTrace:java.lang.RuntimeException
at org.apache.axis.Message.setup(Message.java:361)
at org.apache.axis.Message.<init>(Message.java:235)
at org.apache.axis.transport.http.HTTPSender.readFromSocket(HTTPSender.java:779)
at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:144)
at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)
at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118)
at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83)
at org.apache.axis.client.AxisClient.invoke(AxisClient.java:165)
at org.apache.axis.client.Call.invokeEngine(Call.java:2784)
at org.apache.axis.client.Call.invoke(Call.java:2767)
at org.apache.axis.client.Call.invoke(Call.java:2443)
at org.apache.axis.client.Call.invoke(Call.java:2366)
at org.apache.axis.client.Call.invoke(Call.java:1812)
at com.bluecubs.xinco.client.XincoExplorer.doDataWizard(XincoExplorer.java:2788)
at com.bluecubs.xinco.client.XincoExplorer$8.mousePressed(XincoExplorer.java:1437)
at java.awt.AWTEventMulticaster.mousePressed(AWTEventMulticaster.java:263)
at java.awt.Component.processMouseEvent(Component.java:6035)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
at java.awt.Component.processEvent(Component.java:5803)
at java.awt.Container.processEvent(Container.java:2058)
at java.awt.Component.dispatchEventImpl(Component.java:4410)
at java.awt.Container.dispatchEventImpl(Container.java:2116)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3983)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
at java.awt.Container.dispatchEventImpl(Container.java:2102)
at java.awt.Window.dispatchEventImpl(Window.java:2429)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
{http://xml.apache.org/axis/}hostname:PRAII1371900
java.lang.RuntimeException
at org.apache.axis.AxisFault.makeFault(AxisFault.java:101)
at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:154)
at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)
at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118)
at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83)
at org.apache.axis.client.AxisClient.invoke(AxisClient.java:165)
at org.apache.axis.client.Call.invokeEngine(Call.java:2784)
at org.apache.axis.client.Call.invoke(Call.java:2767)
at org.apache.axis.client.Call.invoke(Call.java:2443)
at org.apache.axis.client.Call.invoke(Call.java:2366)
at org.apache.axis.client.Call.invoke(Call.java:1812)
at com.bluecubs.xinco.client.XincoExplorer.doDataWizard(XincoExplorer.java:2788)
at com.bluecubs.xinco.client.XincoExplorer$8.mousePressed(XincoExplorer.java:1437)
at java.awt.AWTEventMulticaster.mousePressed(AWTEventMulticaster.java:263)
at java.awt.Component.processMouseEvent(Component.java:6035)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
at java.awt.Component.processEvent(Component.java:5803)
at java.awt.Container.processEvent(Container.java:2058)
at java.awt.Component.dispatchEventImpl(Component.java:4410)
at java.awt.Container.dispatchEventImpl(Container.java:2116)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3983)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
at java.awt.Container.dispatchEventImpl(Container.java:2102)
at java.awt.Window.dispatchEventImpl(Window.java:2429)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
Caused by: java.lang.RuntimeException
at org.apache.axis.Message.setup(Message.java:361)
at org.apache.axis.Message.<init>(Message.java:235)
at org.apache.axis.transport.http.HTTPSender.readFromSocket(HTTPSender.java:779)
at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:144)
... 32 moreAnd the related code:
Message m = null;
MessageContext mc = null;
AttachmentPart ap = null;
Call call = (Call)xincoClientSession.xinco_service.createCall();
call.setTargetEndpointAddress(new URL(xincoClientSession.service_endpoint));
call.setOperationName(new QName("urn:Xinco", "downloadXincoCoreData"));
Object[] objp = new Object[2];
objp[0] = (XincoCoreData)newnode.getUserObject();
objp[1] = xincoClientSession.user;
//tell server to send file as attachment
//(keep backward compatibility to earlier versions)
ap = new AttachmentPart();
ap.setContent(new String("SAAJ"), "text/string");
call.addAttachmentPart(ap);
//invoke actual call
byte_array = (byte[])call.invoke(objp);
//get file from SOAP message or byte array
mc = call.getMessageContext();
m = mc.getResponseMessage();
if (m.getAttachments().hasNext()) {
ap = (AttachmentPart)m.getAttachments().next();
in = (InputStream)ap.getContent();
} else {
in = new ByteArrayInputStream(byte_array);
}The stack trace point the error to the line:
*byte_array = (byte[])call.invoke(objp);*
Edited by: javydreamercsw on Oct 19, 2007 1:08 PM -
How to use Javamail for accessing additional mailboxes -IMAP, Exchange 2010
hi,
I want to access a shared mailbox (NOT FOLDER) via Javamail API (1.4.5) using IMAP(s) with plain logon. The mailserver is a Exchange Server 2010.
User: user1 ([email protected])
pwd: xxxx
shared mailbox: [email protected]
Properties:
mail.imaps.socketFactory.port = 993
mail.imaps.starttls.enable = true
mail.imaps.socketFactory.class = javax.net.ssl.SSLSocketFactory
mail.imaps.socketFactory.fallback = false
username = [email protected]
password = xxxx
I´ve managed to get access to the user1 - mailbox:
Session session = Session.getInstance(properties, new ExchangeAuthenticator(username, password));
session.setDebug(true);
Store store = session.getStore("imaps");
store.connect(imapHost, username, password);
--> this works just fine! But now i want to access the additional mailbox by changing the login-String:
[email protected]/shared_MB (user@domain/additional_MB)
--> unfortunately I´m getting an "NO AUTHENTICATE" message:
DEBUG: setDebug: JavaMail version 1.4.5
DEBUG: getProvider() returning javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc]
DEBUG: mail.imap.fetchsize: 16384
DEBUG: mail.imap.statuscachetimeout: 1000
DEBUG: mail.imap.appendbuffersize: -1
DEBUG: mail.imap.minidletime: 10
DEBUG: trying to connect to host "host.domain.com", port 993, isSSL true
* OK The Microsoft Exchange IMAP4 service is ready.
A0 CAPABILITY
* CAPABILITY IMAP4 IMAP4rev1 AUTH=NTLM AUTH=GSSAPI AUTH=PLAIN UIDPLUS CHILDREN IDLE NAMESPACE LITERAL+
A0 OK CAPABILITY completed.
DEBUG IMAP: AUTH: NTLM
DEBUG IMAP: AUTH: GSSAPI
DEBUG IMAP: AUTH: PLAIN
DEBUG: protocolConnect login, host=host.domain.com, [email protected]/shared_MB, password=<non-null>
DEBUG IMAP: AUTHENTICATE PLAIN command trace suppressed
DEBUG IMAP: AUTHENTICATE PLAIN command result: A1 NO AUTHENTICATE failed.
javax.mail.AuthenticationFailedException: AUTHENTICATE failed.
I was able to get access with Thunderbird and also with the Exchange OWA-Client, so I think there is something missing in my code...
or is it just impossible to get access to a different mailbox using javamail and plain-auth?
Thank you in advance.Thanks bshannon, that was a great idea!
I haven´t found an solution yet, but I have maybe identified the real problem:
Here is some interessting Thunderbird - Logging stuff:
744[7161040]: try to log in
744[7161040]: IMAP auth: server caps 0x1187235, pref 0x1006, failed 0x0, avail caps 0x1004
744[7161040]: (GSSAPI = 0x1000000, CRAM = 0x20000, NTLM = 0x100000, MSN = 0x200000, PLAIN = 0x1000, LOGIN = 0x2, old-style IMAP login = 0x4)auth external IMAP login = 0x20000000
744[7161040]: trying auth method 0x1000
744[7161040]: got new password
744[7161040]: IMAP: trying auth method 0x1000
744[7161040]: PLAIN auth
744[7161040]: 7082000:xmail.domain.com:NA:SendData: 2 authenticate plain
744[7161040]: ReadNextLine [stream=7ec9e88 nb=3 needmore=0]
744[7161040]: 7082000:xmail.domain.com:NA:CreateNewLineFromSocket: +
744[7161040]: 7082000:xmail.domain.com:NA:SendData: Logging suppressed for this command (it probably contained authentication information)
744[7161040]: ReadNextLine [stream=7ec9e88 nb=27 needmore=0]
744[7161040]: 7082000:xmail.domain.com:NA:CreateNewLineFromSocket: 2 NO AUTHENTICATE failed.
744[7161040]: authlogin failed
744[7161040]: marking auth method 0x1000 failed
---> okay, so PLAIN AUTH is failing.....
744[7161040]: IMAP auth: server caps 0x1187235, pref 0x1006, failed 0x1000, avail caps 0x4
744[7161040]: (GSSAPI = 0x1000000, CRAM = 0x20000, NTLM = 0x100000, MSN = 0x200000, PLAIN = 0x1000, LOGIN = 0x2, old-style IMAP login = 0x4)auth external IMAP login = 0x20000000
744[7161040]: trying auth method 0x4
744[7161040]: got new password
744[7161040]: IMAP: trying auth method 0x4
744[7161040]: old-style auth
744[7161040]: 7082000:xmail.xmail.domain.com:NA:SendData: Logging suppressed for this command (it probably contained authentication information)
744[7161040]: ReadNextLine [stream=7ec9e88 nb=23 needmore=0]
744[7161040]: 7082000:xmail.domain.com:NA:CreateNewLineFromSocket: 4 OK LOGIN completed.
744[7161040]: login succeeded
--> okay, so Thunderbird is using "old-style IMAP login" and is successful.
Unfortunately I have no idea what that actually means or how to use it in Javamail (is it even supported?). Any suggestions? -
Using JSF and JavaMail to send Automated Email
Hi All,
Can any one please suggest I can use JSF and JavaMail to send automated email messages i.e after a person has successfully completed a form , a message is sent to his/her email address confirming that he has succesfully registered or completed a form. I have succesfull implemeted the use of javamail for sending email meassages in a JSF web application but cant seem to figure out how i can achieve automated sending of emails in JSF. Please any ideas, tutorials or source code would be very much appreciated.
Thanks.I don't understand your problem:
You have already been able to send e-mails from a JSF webapplication, but you are not capable of sending e-mails from a JSF webapplication?!
Automated sending of e-mails will be exactly the same as non-automated. -
Using javamail with dial-up connection and LAN
Hello,
I'm using javamail on Windows XP (including service pack 2). When I connect to a mail server on the network, everything is OK. When I connect to a mail server using a dial-up connection, everything is OK. But when I try to connect to a mail server for which I need the dial-up connection and I also have a network connection to my LAN, the connect to the mailserver failed. It looks like JavaMail is searching the mail server on my LAN instead of on the dial-up connection. Does anybody know if I can configure JavaMail to search on the dial-up connection? Does anybody know if this problem will also occur on systems where I have multiple network cards?
Regards,
MarcoNo Prob!
Enjoy Surfing! -
Sending a notification using MDB, javamail and a scheduler
Hi,
I have this following scenario.
I need to send an email notification to user B from user A.
So, user A fills the required details and adds the notification object to jms/queue
In MessageDriveBean onMessage(), i am getting the notification object from the queue
and i am able to send an email using JavaMail.
Everything is working fine.
Now , if under any conditions, sending notification fails, I need to implement
a scheduler which should try to send the notification within the specified time interval
and if not again adds the notification object to queue.
Can you please help me to implement a scheduler?
Thanks in advance!!!Have a look at this simple schedular below, test by changing the method onMessage() to a main method
and simulate.
Hope this help
Ivo Sumelong
* @author isumelong
public class MessageFromQueueMDBHandler {
* @param args the command line arguments
public void onMessage() {
MessageFromQueueMDBHandler m=new MessageFromQueueMDBHandler();
m.hanldeMessageFromQuue();
public synchronized void hanldeMessageFromQuue()
// Thread.sleep() is not good since its a static method this
// why wait will be best since it controls only the thread
// that received the messgae from the queue
//schedular information read from database
// numberOfTrials,waitingTimeBeforeResending;
// advantage: schedular behaviour could be changed at run time
int numberOfTrials=4;// from database
try {
for(int i=0;i<System.currentTimeMillis();i++)
if(sendMail())
break;
if(i==numberOfTrials)
// send an message to queue
sendMessageToQueue();
notifyAll();
break;
long waitingTimeBeforeResending=1000;// from database
this.wait(waitingTimeBeforeResending);
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
private boolean sendMail()
// java mail API accesses
return true;
private boolean sendMessageToQueue()
// java JMS API accesses
return true;
} -
Selecting the data from database and sending to users using javamail
how to select the records from database table in oracle and send automatically to users using javamail. I am able to send the txt msg. but dont know how to send the selected table data to users automatically.
can anyone suggest how to write the steps with database connection to send msgs containing data to different users
Thank Youusing JDBC..you want to
1. create the connect
2. open the connection
3. query the table for the data
4. loop through the resultset to retrieve rows of data
5. do something with the data
6. email the result
once you have the data, it is up to you to determine the format to send to the user using JavaMail. It is easiest to send plain text
here's a site that give code example (for all steps above relating to JDBC):
http://javaalmanac.com/egs/java.sql/pkg.html -
Using JavaMail with Tomcat and JNDI
I have a web application and I want to make use of JNDI Mail Sessions for sending email in my Web Appln.
I am using Tomcat4.0.1
In my server.xml file I declared a resource as follows:
<Resource name="mail/Session" auth="Container" type="javax.mail.Session"/>
<ResourceParams name="mail/Session">
<parameter>
<name>mail.smtp.host</name>
<value>mail.abc.com</value>
</parameter>
</ResourceParams>
Now Inside my jsp/servlet code i can use something like this:=
// Acquire our JavaMail session object
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
Session session = (Session) envCtx.lookup("mail/Session");
// Prepare our mail message
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
InternetAddress dests[] = new InternetAddress[]
{ new InternetAddress(to) };
message.setRecipients(Message.RecipientType.TO, dests);
message.setSubject(subject);
message.setContent(content, "text/plain");
// Send our mail message
Transport.send(message);
But my smtp mail provider uses Authentication.
So I am looking of some way wherein I can provide the user and password information in the server.xml file itself along with smtp provider.
My Query is How to do this as i dont see any references for using JavaMail sessions using Authentication
Any Help highly appreciated
Thanks
RajIsnt there anyone who can answer this question or its not a question worthwile
Awaiting reply
... -
Problem Sending mails in a loop using JavaMail API
Hello All,
I am sending emails in a loop(one after the other) using JavaMail API,but the problem is, if the first two,three email addresses in the loop are Valid it sends the Email Properly, but if the Fourth or so is Invalid Address it throws an Exception....
"javax.mail.SendFailedException: Sending failed;"
nested exception is:
javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
javax.mail.SendFailedException: 450 <[email protected]>:Recipient address rejected: Domain not found......
So if i want to send hundereds of emails and if one of the Emails inbetween is Invalid the process Stops at that point and i could not send the other emails in the Loop......
How Could i Trap the exception thrown and handle it in such a way, so that the loops continues ..
Is there something with the SMTP Server....?
The code which i am using is as follows....
<Code>...
try {
InitialContext ic = new InitialContext();
Session session = (Session) ic.lookup(JNDINames.MAIL_SESSION);
if (Debug.debuggingOn)
session.setDebug(true);
// construct the message
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(eMess.getEmailSender()));
String to = "";
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to, false));
msg.setRecipients(Message.RecipientType.BCC,
InternetAddress.parse(eMess.getEmailReceiver(), false));
msg.setSubject(eMess.getSubject());
msg.setContent(eMess.getHtmlContents(),"text/plain");
msg.saveChanges();
Transport.send(msg);
} catch (Exception e) {
Debug.print("createAndSendMail exception : " + e);
throw new MailerAppException("Failure while sending mail");
</Code>....
Please give me any suggestions regarding it....and guide me accordingly..
Thanks a million in advance...
Regards
SamHow about something like the code attached here. Be aware it is lifted and edited out of an app we have here so it may require changing to get it to work. If it don't work - don't come asking for help as this is only a rough example of one way of doing it. RTFM - that's how we worked it out!
SH
try {
Transport.send(msg);
// If we get to here then the mail went OK so update all the records in the email as sent
System.out.println("Email sent OK");
catch (MessagingException mex) {
System.out.println("Message error");
Exception ex = mex;
do {
if (ex instanceof SendFailedException) {
if (ex.getMessage().startsWith("Sending failed")) {
// Ignore this message as we want to know the real reason for failure
// If we get an Invalid Address error or a Message partially delivered message process the message
if (ex.getMessage().startsWith("Message partially delivered")
|| ex.getMessage().startsWith("Invalid Addresses")) {
// This message is of interest as we need to process the actual individual addresses
System.out.println(ex.getMessage().substring(0, ex.getMessage().indexOf(";")));
// Now get the addresses from the SendFailedException
SendFailedException sfex = (SendFailedException) ex;
Address[] invalid = sfex.getInvalidAddresses();
if (invalid != null) {
System.out.println("Invalid Addresse(s) found -");
if (invalid.length > 0) {
for (int x = 0; x < invalid.length; x++) {
System.out.println(invalid[x].toString().trim());
Address[] validUnsent = sfex.getValidUnsentAddresses();
if (validUnsent != null) {
System.out.println("Valid Unsent Addresses found -");
if (validUnsent.length > 0) {
for (int x = 0; x < validUnsent.length; x++) {
System.out.println(validUnsent[x].toString().trim());
Address[] validSent = sfex.getValidSentAddresses();
if (validSent != null) {
System.out.println("Valid Sent Addresses found -");
if (validSent.length > 0) {
for (int x = 0; x < validSent.length; x++) {
System.out.println(validSent[x].toString().trim());
if (ex instanceof MessagingException)
ex = ((MessagingException) ex).getNextException();
else {
// This is a general catch all and we should assume that no messages went and should stop
System.out.println(ex.toString());
throw ex;
} while (ex != null); -
Problem sending email using javamail in servlet
I try this code and make some changes of my own http://forums.sun.com/thread.jspa?threadID=695781.
When i run the program the confirmtaion shows that the mail has been sent, but when i check in my inbox there's no the message. I'm using gmail and need to authenticate the username and password. I guess the error caused in the servlet.
Here's the code for my servlet :
import java.io.*;
import java.util.Properties;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.mail.internet.*;
import javax.mail.*;
public class ServletEx extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
System.out.println("____emailservlet.doPost");
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
System.out.println("______________________________");
out.println();
String to = request.getParameter("to");
System.out.println("____________________________to" + to);
String subject = request.getParameter("subject");
String msg = request.getParameter("msg");
// construct an instance of EmailSender
System.out.println("servlet_to" + to);
send(username, to, subject, msg);
//send("[email protected]", to, subject, msg);
out.println("mail sent....");
String username = "[email protected]";
String password = "my_password";
String smtp = "smtp.gmail.com";
String port = "587";
public void send(String username, String to, String subject, String msg) {
Properties props = new Properties();
props.put("mail.smtp.user", username);
props.put("mail.smtp.host", smtp);
props.put("mail.smtp.port", port);
props.put("mail.smtp.starttls.enable","true"); // just in case, but not currently necessary, oddly enough
props.put("mail.smtp.auth", "true");
//props.put("mail.smtp.debug", "true");
props.put("mail.smtp.socketFactory.port", port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
SecurityManager security = System.getSecurityManager();
try
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
//session.setDebug(true);
MimeMessage message = new MimeMessage(session);
message.setText(msg);
message.setSubject(subject);
message.setFrom(new InternetAddress(username));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
Transport.send(message);
catch (Exception mex)
mex.printStackTrace();
public class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication(String username, String password)
return new PasswordAuthentication(username, password);
}Actually it's been a long time for me to develope this program, especially with the authenticate smtp. Any help would be very appreciated :)Accordingly to your stackTrace, I think that you miss some utility jar from Geronimo app. server.
As you are using Application server that is J2EE compliant, so there is an own JavaMail implementation embeded and used by the Server. To fix this problem you have to find and add to your calsspath a jar-file that contains Base64EncoderStream.class -
Hi all,
I'd like to know if it's possible and how to use JavaMail 1.4 with Oracle Application Server 10g (9.0.4.0.0), Windows version.
With the following code, I can see that the mail.jar used by the server is the one included in the jdk installation :
// I'm testing InternetAddress.class because I want to use commons-email-1.2.jar that requires mail.jar 1.4 (or higher) and activation.jar 1.1 (or higher)
// and I know that inside the commons-email-1.2.jar file, I need to call the InternetAddress.validate() method that throws a java.lang.NoSuchMethodError: javax.mail.internet.InternetAddress.validate()V if it is used with mail.jar 1.2.
Class cls = javax.mail.internet.InternetAddress.class;
java.security.ProtectionDomain pDomain = cls.getProtectionDomain();
java.security.CodeSource cSource = pDomain.getCodeSource();
java.net.URL location = cSource.getLocation();
System.out.println(location.toString());
This code returns : file:/C:/oracle/app/jdk/jre/lib/ext/mail.jar and this mail.jar file has an implementation version number: 1.2
- I've tried to include my own mail.jar (1.4.2) and activation.jar (1.1.1) files in the war file that I deploy, but it doesn't work (the server still uses the same mail.jar 1.2)
- I've tried to put the mail.jar (1.4.2) and activation.jar (1.1.1) files in the applib directory of my OC4J instance, but it doesn't work (the server still uses the same mail.jar 1.2)
- I know that a patch exists : I've read the following document: How to Make Libraries such as mail.jar and activation.jar Swappable ? [ID 552432.1]
This article talks about the Patch 6514136, but this patch only applies to : Oracle Containers for J2EE - Version: 10.1.3.3.0
Can you please help me ?
Thanks in advance for your answers,
LaurentI strongly suggest to upgrade to AS 10.1.3 to get this.
Think of future support of AS 9.0.4. You will get not critical patch updates anymore.
--olaf -
Error while using Javamail...pls help me...
when i am using javamail for sending mail , i am getting error like,
C:\jdk1.3\bin\mail>java MailSend
[email protected] [email protected]
javax.mail.SendFailedException: Sending failed;
nested exception is:
javax.mail.MessagingException:
at javax.mail.Transport.send0(Transport.java:218)
at javax.mail.Transport.send(Transport.java:80)
at MailSend.Send(MailSend.java:56)
at MailSend.main(MailSend.java:73)
and i define properties like,
mailProp.put("java", "java");
where , "java" is my system name, and there is also mail server on my system. and my system is connected with proxy server..
when i am trying
mailProp.put("mail.smtp.host", "java");
then i am getting same type of error...
so, what is that ? pls help me to solve my error...Surely there's more information associated with that MessaginException than
you've included here.
Turn on session debugging and run your program again.
http://java.sun.com/products/javamail/FAQ.html#debug -
Sending Attachments using JavaMail
I trying to send attachments using JavaMail API which is loaded into an oracle 8.1.7 database as a stored procedure, the code looks like this:-
CREATE OR REPLACE AND COMPILE JAVA SOURCE NAMED "SendMail" AS
import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendMail {
// Sender, Recipient, CCRecipient, and BccRecipient are comma-
// separated lists of addresses;
// Body can span multiple CR/LF-separated lines;
// Attachments is a ///-separated list of file names;
public static int Send(String SMTPServer,
String Sender,
String Recipient,
String CcRecipient,
String BccRecipient,
String Subject,
String Body,
String ErrorMessage[],
String Attachments) {
// Error status;
int ErrorStatus = 0;
// create some properties and get the default Session;
Properties props = System.getProperties();
props.put("mail.smtp.host", SMTPServer);
Session session = Session.getDefaultInstance(props, null);
try {
// create a message;
MimeMessage msg = new MimeMessage(session);
// extracts the senders and adds them to the message;
// Sender is a comma-separated list of e-mail addresses as
// per RFC822;
InternetAddress[] TheAddresses =
InternetAddress.parse(Sender);
msg.addFrom(TheAddresses);
// extract the recipients and assign them to the message;
// Recipient is a comma-separated list of e-mail addresses
// as per RFC822;
InternetAddress[] TheAddresses =
InternetAddress.parse(Recipient);
msg.addRecipients(Message.RecipientType.TO,
TheAddresses);
// extract the Cc-recipients and assign them to the
// message;
// CcRecipient is a comma-separated list of e-mail
// addresses as per RFC822;
if (null != CcRecipient) {
InternetAddress[] TheAddresses =
InternetAddress.parse(CcRecipient);
msg.addRecipients(Message.RecipientType.CC,
TheAddresses);
// extract the Bcc-recipients and assign them to the
// message;
// BccRecipient is a comma-separated list of e-mail
// addresses as per RFC822;
if (null != BccRecipient) {
InternetAddress[] TheAddresses =
InternetAddress.parse(BccRecipient);
msg.addRecipients(Message.RecipientType.BCC,
TheAddresses);
// subject field;
msg.setSubject(Subject);
// create the Multipart to be added the parts to;
Multipart mp = new MimeMultipart();
// create and fill the first message part;
MimeBodyPart mbp = new MimeBodyPart();
mbp.setText(Body);
// attach the part to the multipart;
mp.addBodyPart(mbp);
// attach the files to the message;
if (null != Attachments) {
int StartIndex = 0, PosIndex = 0;
while (-1 != (PosIndex = Attachments.indexOf("///",
StartIndex))) {
// create and fill other message parts;
MimeBodyPart mbp = new MimeBodyPart();
FileDataSource fds =
new FileDataSource(Attachments.substring(StartIndex,
PosIndex));
mbp.setDataHandler(new DataHandler(fds));
mbp.setFileName(fds.getName());
mp.addBodyPart(mbp);
PosIndex += 3;
StartIndex = PosIndex;
// last, or only, attachment file;
if (StartIndex < Attachments.length()) {
MimeBodyPart mbp = new MimeBodyPart();
FileDataSource fds =
new FileDataSource(Attachments.substring(StartIndex));
mbp.setDataHandler(new DataHandler(fds));
mbp.setFileName(fds.getName());
mp.addBodyPart(mbp);
// 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 MsgException) {
ErrorMessage[0] = MsgException.toString();
Exception TheException = null;
if ((TheException = MsgException.getNextException()) !=
null)
ErrorMessage[0] = ErrorMessage[0] + "\n" +
TheException.toString();
ErrorStatus = 1;
return ErrorStatus;
show errors java source "SendMail"
CREATE OR REPLACE PACKAGE SendMailJPkg AS
-- EOL is used to separate text line in the message body;
EOL CONSTANT STRING(2) := CHR(13) || CHR(10);
TYPE ATTACHMENTS_LIST IS
TABLE OF VARCHAR2(4000);
-- high-level interface with collections;
FUNCTION SendMail(SMTPServerName IN STRING,
Sender IN STRING,
Recipient IN STRING,
CcRecipient IN STRING DEFAULT '',
BccRecipient IN STRING DEFAULT '',
Subject IN STRING DEFAULT '',
Body IN STRING DEFAULT '',
ErrorMessage OUT STRING,
Attachments IN ATTACHMENTS_LIST DEFAULT NULL)
RETURN NUMBER;
END SendMailJPkg;
show errors
CREATE OR REPLACE PACKAGE BODY SendMailJPkg AS
PROCEDURE ParseAttachment(Attachments IN ATTACHMENTS_LIST,
AttachmentList OUT VARCHAR2) IS
AttachmentSeparator CONSTANT VARCHAR2(12) := '///';
BEGIN
-- boolean short-circuit is used here;
IF Attachments IS NOT NULL AND Attachments.COUNT > 0 THEN
AttachmentList := Attachments(Attachments.FIRST);
-- scan the collection, skip first element since it has been
-- already processed;
-- accommodate for sparse collections;
FOR I IN Attachments.NEXT(Attachments.FIRST) ..
Attachments.LAST LOOP
AttachmentList := AttachmentList || AttachmentSeparator ||
Attachments(I);
END LOOP;
ELSE
AttachmentList := '';
END IF;
END ParseAttachment;
-- forward declaration;
FUNCTION JSendMail(SMTPServerName IN STRING,
Sender IN STRING,
Recipient IN STRING,
CcRecipient IN STRING,
BccRecipient IN STRING,
Subject IN STRING,
Body IN STRING,
ErrorMessage OUT STRING,
Attachments IN STRING) RETURN NUMBER;
-- high-level interface with collections;
FUNCTION SendMail(SMTPServerName IN STRING,
Sender IN STRING,
Recipient IN STRING,
CcRecipient IN STRING,
BccRecipient IN STRING,
Subject IN STRING,
Body IN STRING,
ErrorMessage OUT STRING,
Attachments IN ATTACHMENTS_LIST) RETURN NUMBER IS
AttachmentList VARCHAR2(4000) := '';
AttachmentTypeList VARCHAR2(2000) := '';
BEGIN
ParseAttachment(Attachments,
AttachmentList);
RETURN JSendMail(SMTPServerName,
Sender,
Recipient,
CcRecipient,
BccRecipient,
Subject,
Body,
ErrorMessage,
AttachmentList);
END SendMail;
-- JSendMail's body is the java function SendMail.Send();
-- thus, no PL/SQL implementation is needed;
FUNCTION JSendMail(SMTPServerName IN STRING,
Sender IN STRING,
Recipient IN STRING,
CcRecipient IN STRING,
BccRecipient IN STRING,
Subject IN STRING,
Body IN STRING,
ErrorMessage OUT STRING,
Attachments IN STRING) RETURN NUMBER IS
LANGUAGE JAVA
NAME 'SendMail.Send(java.lang.String,
java.lang.String,
java.lang.String,
java.lang.String,
java.lang.String,
java.lang.String,
java.lang.String,
java.lang.String[],
java.lang.String) return int';
END SendMailJPkg;
show errors
var ErrorMessage VARCHAR2(4000);
var ErrorStatus NUMBER;
-- enable SQL*PLUS output;
SET SERVEROUTPUT ON
-- redirect java output into SQL*PLUS buffer;
exec dbms_java.set_output(5000);
BEGIN
:ErrorStatus := SendMailJPkg.SendMail(
SMTPServerName => 'gmsmtp03.oraclecorp.com',
Sender => '[email protected]',
Recipient => '[email protected]',
CcRecipient => '',
BccRecipient => '',
Subject => 'This is the subject line: Test JavaMail',
Body => 'This is the body: Hello, this is a test' ||
SendMailJPkg.EOL || 'that spans 2 lines',
ErrorMessage => :ErrorMessage,
Attachments => SendMailJPkg.ATTACHMENTS_LIST(
'/tmp/on.lst',
'/tmp/sqlnet.log.Z'
END;
print
If I try and send file as attachments from the tmp directory, then everything works ok, but if I try to send the same file from any other directory, then it doesn't work. Can anyone help? Is there something wrong with the code, I'm not aware of anything that would make it directory specfic. Permissions are the same on /tmp as the new directory /NRS/Data/SystemX which I'm trying to send the file from now.well
if u see the end of ur mail it shows the attachment dir there in which u have specified the address..why don't u do a change there or better have some in parameteres in the procedure for it..that would help in choosing the attachment directory on users wish?
hope i am getting the problem right..if not kindly correct me in understanding the problem.
thanX. -
Best practice for using javaMail
greetings,
On my website, I am using several forms (embedded in jsp pages) that will email their data to a specified email address. To do this I am using javaMail.
Right now, I am able to embed the following code (code similar to it) in a processor page that is set as the action of the form that will email the data and then redirect the user to the "success" page.
Properties props = new Properties();
props.put("mail.smtp.host", "localhost");
Session s = Session.getInstance(props,null);
MimeMessage message = new MimeMessage(s);
InternetAddress from = new InternetAddress("[email protected]");
message.setFrom(from);
InternetAddress to = new InternetAddress("[email protected]");
message.addRecipient(Message.RecipientType.TO, to);
message.setSubject("Test");
message.setText(request.getParameter("message"));
Transport.send(message);
response.sendRedirect("/success.jsp");
I'm positive there is a more efficient way to do this than to duplicate this code with minor tweaks for each form on my site. Is this something that is best put into a class that will accept arguements like "to", "from", "subject", "message", etc? Then I can just call that method from any jsp page that gets the form values? or should this be treated as a servlet that the form itself submits to . . .? or something else that I don't even know of . . .?
Any insight is greatly appreciated.
-dHi dpassudetti,
Yes there is a better way of doing it. What u can do is use a Java Bean which will have get/set methods for arguements like "to", "from", "subject", "message" etc.And then have a method sendMessage() and put this code in it :
public boolean sendMessage() {
Properties props = new Properties();
props.put("mail.smtp.host", "localhost");
Session s = Session.getInstance(props,null);
MimeMessage message = new MimeMessage(s);
InternetAddress from = new InternetAddress("[email protected]");
message.setFrom(from);
InternetAddress to = new InternetAddress("[email protected]");
message.addRecipient(Message.RecipientType.TO, to);
message.setSubject("Test");
message.setText(request.getParameter("message"));
Transport.send(message);
return true;
And in ur jsp, if redirect it to ur JSP file if it returns true.
hope this helps..
Sachin -
How to bypass proxy when trying to send a mail using javamail smtp
Hi,
I am trying to make a servlet send a mail using javamail smtp protocol on port 25 but i m not able to send getting an exception, i suspect proxy is blocking, so any idea anyone how bypass a proxy.And if it does turn out that there's a proxy server blocking access to your target SMTP server, the best way to deal with that is to discuss the issue with the person responsible for your network configuration.
Maybe you are looking for
-
Open directory Server admin APP, crashes
HI all. ON my 10.7.2 lion server for some reason my server admin app keeps crashing under the Open directory Section... Here are the screen shots..
-
Hi! Ok, so I uploaded some videos into my itunes and i want to classify them as a TV Show. However when I do that, it doesn't let me input its Show Name, or Season or anything besides the title. Even under artist and album I put the info and it doesn
-
When I edit the names of artists on the new iTunes, sometimes it doesn't change the name when it shows the album artwork with the name underneath (when it sorts by album) or when it shows as if you were flipping through cds. How can I get it to show
-
Hi, I am using a personal domain name with iweb for one site. I have created two other sites using name forwarding. When I publish one of the other two I get the option to 'visit site now'. When I click on this it takes me to my first personal domain
-
Missing Horizontal scroll bar in Side Bar of Firefox 4
When I use the FF4 Side Bar for my Bookmarks, I cannot see many of my '''Sub-Folders or read long link names''' because there is '''no Horizontal Scroll Bar'''. Instead, I must '''manually widen''' the Side Bar to see the longer link names or expande