Sending a Directory using JavaMail
Hi. Can anyone tell me how to send a directory using JavaMail? Thanks.
what you can do is create a file object and load all the files one by one and attach them as a multipart object to the same mail.
anurag
Similar Messages
-
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.
-
How to send secure email using JavaMail
Hi, anyone out there know how to send secure email using Java Mail? Greately appreciated.
For starters, if you have not already done so, read about it in the JavaMail design specifications.
Search for Message Security in the said document. -
Send THAI mail using JavaMail to Lotus Notes (URGENT)
Hi all
I experienced the problem when I try to use Javamail to send mail that contains THAI text to Lotus Notes . When I read my mail in Lotus Note,I cannot read it !! . What should I do ?
Please suggest .
Regards
Chairat Tiajanpan
E-Mail : [email protected]� hello!
Do you know how can I do it? I am desesperated. Please help me.
I want to send a mail to lotus notes using a Java class.
What i need to install in my computer for running the class??
Sorry for my english. I am spanish and i speak english very bad.
Thanks!! -
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 -
Trying to send e-mail using JavaMail, JBoss 5, and JNDI
Hello there,
Am using JBoss 5.1.0GA and JDK 1.5.0_19 on OS X Leopard.
Created a working SendMailServlet.
Have now decided to refactor it into two separate classes (extract out JavaMail code to a separate class and create a ServletController).
Am also trying to use JNDI to access the connection properties in the mail-service.xml configuration file residing in JBoss.
The Mailer class contains the reusable functionality needed to send an e-mail:
public class Mailer {
private Session mailSession;
protected void sendMsg(String email, String subject, String body)
throws MessagingException, NamingException {
Properties props = new Properties();
InitialContext ictx = new InitialContext(props);
Session mailSession = (Session) ictx.lookup("java:/Mail");
// Session mailSessoin = Session.getDefaultInstance(props);
String username = (String) props.get("mail.smtps.user");
String password = (String) props.get("mail.smtps.password");
MimeMessage message = new MimeMessage(mailSession);
message.setSubject(subject);
message.setRecipients(javax.mail.Message.RecipientType.TO,
javax.mail.internet.InternetAddress.parse(email, false));
message.setText(body);
message.saveChanges();
Transport transport = mailSession.getTransport("smtps");
try {
transport.connect(username, password);
transport.sendMessage(message, message.getAllRecipients());
Logger.getLogger(this.getClass()).warn("Message sent");
finally {
transport.close();
}The MailController class serves as a standard Java Servlet which invokes the Mailer.class's sendMsg() method:
public class MailController extends HttpServlet {
/** static final HTML setting for content type */
private static final String HTML = "text/html";
myapp/** static final HTML setting for content type */
private static final String PLAIN = "text/plain";
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(PLAIN);
PrintWriter out = response.getWriter();
String mailToken = TokenUtil.getEncryptedKey();
String body = "Hello there, " + "\n\n"
+ "Wanna play a game of golf?" + "\n\n"
+ "Please confirm: https://localhost:8443/myapp/confirm?token="
+ mailToken + "\n\n" + "-Golf USA";
Mailer mailer = new Mailer();
try {
mailer.sendMsg("[email protected]", "Golf Invitation!", body);
out.println("Message Sent");
catch (MessagingException e) {
e.printStackTrace();
catch (NamingException e) {
e.printStackTrace();
}Have the mail configuration set under $JBOSS_HOME/server/default/deploy/mail-service.xml:
<server>
<mbean code="org.jboss.mail.MailService" name="jboss:service=Mail">
<attribute name="JNDIName">java:/Mail</attribute>
<attribute name="User">user</attribute>
<attribute name="Password">password</attribute>
<attribute name="Configuration">
<configuration>
<property name="mail.store.protocol" value="pop3"/>
<property name="mail.transport.protocol" value="smtp"/>
<property name="mail.user" value="user"/>
<property name="mail.pop3.host" value="pop3.gmail.com"/>
<property name="mail.smtp.host" value="smtp.gmail.com"/>
<property name="mail.smtp.port" value="25"/>
<property name="mail.from" value="[email protected]"/>
<property name="mail.debug" value="true"/>
</configuration>
</attribute>
<depends>jboss:service=Naming</depends>
</mbean>
</server>web.xml (Deployment Descriptor):
<servlet>
<servlet-name>MailController</servlet-name>
<servlet-class>com.myapp.MailController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MailController</servlet-name>
<url-pattern>/sendmail</url-pattern>
</servlet-mapping>This is what is outputted when I start JBOSS and click point my browser to:
https://localhost:8443/myapp/sendmail
[MailService] Mail Service bound to java:/Mail
[STDOUT] DEBUG: JavaMail version 1.4ea
[STDOUT] DEBUG: java.io.FileNotFoundException:
/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Home/lib/javamail.providers
(No such file or directory)
[STDOUT] DEBUG: !anyLoaded
[STDOUT] DEBUG: not loading resource: /META-INF/javamail.providers
[STDOUT] DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
[STDOUT] DEBUG: getProvider() returning
javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc]
[STDOUT] DEBUG SMTP: useEhlo true, useAuth false
[STDOUT] DEBUG SMTP: trying to connect to host "localhost", port 465, isSSL true
[STDERR] javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 465;
nested exception is:
java.net.ConnectException: Connection refused
[STDERR] at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1282)
[STDERR] at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:370)
[STDERR] at javax.mail.Service.connect(Service.java:275)
[STDERR] at javax.mail.Service.connect(Service.java:156)
[STDERR] at javax.mail.Service.connect(Service.java:176)
[STDERR] at com.myapp.Mailer.sendMsg(Mailer.java:45)
[STDERR] at com.myapp.MailController.doPost(MailController.java:42)
[STDERR] at com.myapp.MailController.doGet(MailController.java:26)Why am I getting this java.net.ConnectException: Connection refused exception?
Happy programming,
Mike
Edited by: mwilson72 on Aug 21, 2009 4:49 PMHi Peter,
Nice to hear from you again!
Per your advice, this is what my mail-service.xml config file looks like now:
<?xml version="1.0" encoding="UTF-8"?>
<server>
<mbean code="org.jboss.mail.MailService" name="jboss:service=Mail">
<attribute name="JNDIName">java:/Mail</attribute>
<attribute name="User">user</attribute>
<attribute name="Password">password</attribute>
<attribute name="Configuration">
<configuration>
<property name="mail.store.protocol" value="pop3"/>
<property name="mail.transport.protocol" value="smtps"/>
<property name="mail.smtp.starttls.enable" value="true"/>
<property name="mail.smtps.auth" value="true"/>
<property name="mail.user" value="user"/>
<property name="mail.pop3.host" value="pop3.gmail.com"/>
<property name="mail.smtp.host" value="smtp.gmail.com"/>
<property name="mail.smtps.port" value="465"/>
<property name="mail.from" value="[email protected]"/>
<property name="mail.debug" value="true"/>
</configuration>
</attribute>
<depends>jboss:service=Naming</depends>
</mbean>
</server>Now, when I restart JBoss and point my browser to:
https://localhost:8443/myapp/sendmail
I get this exception:
[STDOUT] DEBUG SMTP: useEhlo true, useAuth true
[STDOUT] DEBUG SMTP: useEhlo true, useAuth true
[STDOUT] DEBUG SMTP: trying to connect to host "localhost", port 465, isSSL true
[STDERR] javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 465;
nested exception is:
java.net.ConnectException: Connection refused
[STDERR] at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1282)
[STDERR] at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:370)
[STDERR] at javax.mail.Service.connect(Service.java:297)
[STDERR] at javax.mail.Service.connect(Service.java:156)
[STDERR] at javax.mail.Service.connect(Service.java:176)
[STDERR] at com.myapp.Mailer.sendMsg(Mailer.java:45)
[STDERR] at com.myapp.MailController.doPost(MailController.java:42)
[STDERR] at com.myapp.MailController.doGet(MailController.java:26)Does anyone know what I am possibly doing wrong? Is it my code or is it the config file?
-Mike -
Getting error when sending SMTP mail using javamail api
hi all
i am new to javamail api...and using it first-time....i'v used the following code
<%
String mailHost="mail.mastsale.com";
String mailText="Hello this is a test msg";
String to="<a href="mailto:[email protected]">[email protected]</a>";
String subject="jsp test mail";
try
String from="<a href="mailto:[email protected]">[email protected]</a>";
String mailhost = "mail.mastsale.com";
Properties props = System.getProperties();
props.put("mail.smtp.host", mailhost);
// Get a Session object
Authenticator auth = new SMTPAuthenticator( "<a href="mailto:[email protected]">[email protected]</a>", "abcd" );
Session session1 = Session.getInstance(props,auth);
//Session.setDebug(true);
//construct message
Message msg = new MimeMessage(session1);
msg.setFrom(new InternetAddress(from,"Your Name"));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
msg.setSubject(subject);
msg.setText(mailText);
//msg.setHeader("X-Mailer",mailer);
msg.setSentDate(new Date());
msg.saveChanges();
//Send the message
out.println("Sending mail to " + to);
Transport.send(msg);
catch (MessagingException me)
out.println("Error in sending message for messaging exception:"+me);
%>
and
SMTPAuthenticator.java
import java.io.*;
import java.util.*;
import java.lang.*;
import javax.mail.*;
import javax.mail.internet.*;
public class SMTPAuthenticator extends javax.mail.Authenticator {
private String fUser;
private String fPassword;
public SMTPAuthenticator(String user, String password) {
fUser = user;
fPassword = password;
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fUser, fPassword);
Now getting error as: Error in sending message for messaging exception:javax.mail.SendFailedException: Invalid Addresses; nested exception is: com.sun.mail.smtp.SMTPAddressFailedException: 550-(host.hostonwin.com) [208.101.41.106] is currently not permitted to relay 550-through this server. Perhaps you have not logged into the pop/imap server 550-in the last 30 minutes or do not have SMTP Authentication turned on in your 550 email client.
Can anyone help me?i got the following error while using the below code,
-----------registerForm----------------
DEBUG: setDebug: JavaMail version 1.3.2
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
:::::::::::::::::::::::::::::::::<FONT SIZE=4 COLOR="blue"> <B>Error : </B><BR><HR> <FONT SIZE=3 COLOR="black">javax.mail.AuthenticationFailedException<BR><HR>
-----------registerForm----------------
public class SendMailBean {
public String send(String p_from, String p_to, String p_cc, String p_bcc,
String p_subject, String p_message, String p_smtpServer,String FilePath) {
String l_result = "";
// Name of the Host machine where the SMTP server is running
String l_host = p_smtpServer;
//for file attachment
String filename = FilePath;
// Gets the System properties
Properties l_props = System.getProperties();
// Puts the SMTP server name to properties object
l_props.put("mail.smtp.host", l_host);
l_props.put("mail.smtp.auth", "true");
// Get the default Session using Properties Object
Session l_session = Session.getDefaultInstance(l_props, null);
l_session.setDebug(true); // Enable the debug mode
try {
MimeMessage l_msg = new MimeMessage(l_session); // Create a New message
l_msg.setFrom(new InternetAddress(p_from)); // Set the From address
// Setting the "To recipients" addresses
l_msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(p_to, false));
// Setting the "Cc recipients" addresses
l_msg.setRecipients(Message.RecipientType.CC,
InternetAddress.parse(p_cc, false));
// Setting the "BCc recipients" addresses
l_msg.setRecipients(Message.RecipientType.BCC,
InternetAddress.parse(p_bcc, false));
l_msg.setSubject(p_subject); // Sets the Subject
// Create and fill the first message part
MimeBodyPart l_mbp = new MimeBodyPart();
//123
///////l_mbp.setText(p_message);
l_mbp.setContent(p_message,"text/html");
// Create the Multipart and its parts to it
Multipart l_mp = new MimeMultipart();
//l_mp.setContent(html,"text/html");
l_mp.addBodyPart(l_mbp);
// Add the Multipart to the message
l_msg.setContent(l_mp,"text/html");
// Set the Date: header
l_msg.setSentDate(new Date());
//added by cibijaybalan for file attachment
// attach the file to the message
//Multipart l_mp1 = new MimeMultipart();
if(!filename.equals(""))
String fname = filename;
MimeBodyPart mbp2 = new MimeBodyPart();
FileDataSource fds = new FileDataSource(fname);
mbp2.setDataHandler(new DataHandler(fds));
mbp2.setFileName(fds.getName());
l_mp.addBodyPart(mbp2);
// add the Multipart to the message
l_msg.setContent(l_mp);
//ends here
l_msg.setSentDate(new java.util.Date());
// Send the message
Transport.send(l_msg);
// If here, then message is successfully sent.
// Display Success message
l_result = l_result + "Mail was successfully sent to : "+p_to;
//if CCed then, add html for displaying info
//if (!p_cc.equals(""))
//l_result = l_result +"<FONT color=green><B>CCed To </B></FONT>: "+p_cc+"<BR>";
//if BCCed then, add html for displaying info
//if (!p_bcc.equals(""))
//l_result = l_result +"<FONT color=green><B>BCCed To </B></FONT>: "+p_bcc ;
//l_result = l_result+"<BR><HR>";
} catch (MessagingException mex) { // Trap the MessagingException Error
// If here, then error in sending Mail. Display Error message.
l_result = l_result + "<FONT SIZE=4 COLOR=\"blue\"> <B>Error : </B><BR><HR> "+
"<FONT SIZE=3 COLOR=\"black\">"+mex.toString()+"<BR><HR>";
} catch (Exception e) {
// If here, then error in sending Mail. Display Error message.
l_result = l_result + "<FONT SIZE=4 COLOR=\"blue\"> <B>Error : </B><BR><HR> "+
"<FONT SIZE=3 COLOR=\"black\">"+e.toString()+"<BR><HR>";
e.printStackTrace();
}//end catch block
//finally {
System.out.println(":::::::::::::::::::::::::::::::::"+l_result);
return l_result;
} // end of method send
} //end of bean
plz help me -
Sending an Email using JavaMail from the Net Work of my company not workin
Hi,
If any body would reply to this issue as soon as possible..
I have developed a simple java mail program which sends an email to gmail (smtp.gmail.com) and works fine at home , So when i sent the same
from my office(at company) it did not work and exception was reported saying ...... could not connect to host .smtp.gmail.com... port .. .
I think it's a network problem.
So If any body has a suggestion ?
If so can any body give a simple code for this issue.
Regards,No, I don't mean the msgshow.java demo program. I mean the [JavaMail FAQ|http://java.sun.com/products/javamail/FAQ.html].
In particular, the section about debugging connection problems and the section
about connecting to Gmail.
Find it yet? -
How to Send Html Email using JavaMail?
I want to send email message body as html.
as some news sites send.What will easiest way of doing that?oops!!!
Sorry there is one more thing in it the ByteArrayDataSource class. I am posting the code in the class here. Compile it in a separate class.
class ByteArrayDataSource implements DataSource
private byte[] data; // data
private String type; // content-type
/* Create a DataSource from an input stream */
public ByteArrayDataSource(InputStream is, String type)
this.type = type;
try
ByteArrayOutputStream os = new ByteArrayOutputStream();
int ch;
while ((ch = is.read()) != -1)
// XXX - must be made more efficient by
// doing buffered reads, rather than one byte reads
os.write(ch);
data = os.toByteArray();
} catch (IOException ioex) { }
/* Create a DataSource from a byte array */
public ByteArrayDataSource(byte[] data, String type)
this.data = data;
this.type = type;
/* Create a DataSource from a String */
public ByteArrayDataSource(String data, String type)
try
// Assumption that the string contains only ASCII
// characters! Otherwise just pass a charset into this
// constructor and use it in getBytes()
this.data = data.getBytes("iso-8859-1");
catch (UnsupportedEncodingException uex)
this.type = type;
* Return an InputStream for the data.
* Note - a new stream must be returned each time.
public InputStream getInputStream() throws IOException
if (data == null)
throw new IOException("no data");
return new ByteArrayInputStream(data);
public OutputStream getOutputStream() throws IOException
throw new IOException("cannot do this");
public String getContentType()
return type;
public String getName()
return "dummy";
}hope this will help
best wishes
khuda hafiz -
Sending flash content using javamail
hi
i have been trying to send a flash content by attaching the flash file and referencing in thru the "cid: " referance. This works very well with outlook express but fails in outlook2000. Could you suggest how this can be taken care of? Such a strategy for images works in outlook 2000. Local and web referances to the flash file also works.
Thanks in advance..
looking forward to some advice
DAHi buddy i am also facing the same prob if you have got the solution then please advice me as i require it urgently..
Rajesh -
Getting exceptions while sending mail using javamail api
Hi to all
I am developing an application of sending a mail using JavaMail api. My program is below:
quote:
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class sms
public static void main(String args[])
try
String strstrsmtserver="smtp.bol.net.in";
String strto="[email protected]";
String strfrom="[email protected]";
String strsubject="Hello";
String bodytext="This is my first java mail program";
sms s=new sms();
s.send(strstrsmtserver,strto,strfrom,strsubject,bodytext);
catch(Exception e)
System.out.println("usage:java sms"+"strstrsmtpserver tosddress fromaddress subjecttext bodyText");
System.exit(0);
public void send(String strsmtpserver,String strto,String strfrom ,String strsubject,String bodytext)
try
java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Properties p=new Properties(System.getProperties());
if(strsmtpserver!=null)
p.put("mail.transport.protocol","smtp");
p.put("mail.smtp.host","[email protected]");
p.put("mail.smtp.port","25");
Session session=Session.getDefaultInstance(p);
Message msg=new MimeMessage(session);
Transport trans = session.getTransport("smtp");
trans.connect("smtp.bol.net.in","[email protected]","1234563757");
msg.setFrom(new InternetAddress(strfrom));
msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(strto,false));
msg.setSubject(strsubject);
msg.setText(bodytext);
msg.setHeader("X-Mailer","mtnlmail");
msg.setSentDate(new Date());
Transport.send(msg);
System.out.println("Message sent OK.");
catch(Exception ex)
System.out.println("here is error");
ex.printStackTrace();
It compiles fine but showing exceptions at run time.Please help me to remove these exceptions.I am new to this JavaMail and it is my first program of javamail.Please also tell me how to use smtp server.I am using MTNL 's internet connection having smtp.bol.net.in server.
exceptions are:
Here is exception
quote:
Javax.mail.MessagingException:Could not connect to SMTP host : smtp.bol.net.in, port :25;
Nested exception is :
Java.net.ConnectException:Connection refused: connect
At com.sun.mail.smtp.SMTPTransport.openServer<SMTPTransport.java:1227>
At com.sun.mail.smtp.SMTPTransport.protocolConnect<SMTPTransport.java:322>
At javax.mail.Service .connect(Service.java:236>
At javax.mail.Service.connect<Service.java:137>
At sms.send<sms.java:77>
At sms.main<sms.java:24>Did you find the JavaMail FAQ?
You should talk to your ISP to get the details for connecting to your server.
In this case I suspect your server wants you to make the connection on the
secure port. The FAQ has examples of how to do this for GMail and Yahoo
mail, which work similarly. By changing the host name, these same examples
will likely work for you. -
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;
} -
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. -
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); -
How to setup SMTP server in PC so as to send mails using JavaMail
Hi,
From forums i got it cleared that we can use JavaMail to send emails. I also got two sample codes about getting it done. But in the code its asks address of the host of SMTP server. I dont have any SMTP server. But i am writing a Library Application in which an email must be sent to users automatically when thier books are in overdue.
Where can i get SMTP server to be installed on my PC so that i can use it send mails through Javamail API.
ThanksIsnt there any way setup SMTP server on own pc?? I just want to send mails in my local area network.
Maybe you are looking for
-
T60p does not boot from new primary hard disk (Single-boot Linux/Fedora 14)
Hi, I have just upgraded the primary disk in my T60p laptop (model 8742-C4G.) The BIOS recognised the disk fine, I partitioned it, marked the first partition as bootable, and then copied the OS (Fedora 14) and all my data back onto it. Then I install
-
How to connect to HP printer model 7500
How do I,connect ,my ,iPad to my, HP e- printer, model 7520?
-
Hi Sirs Need One Big Help With 8520
Hi Have Some 8520 Hang In Logo .Have Wipe And Update By App Loader But Same Problem .Have Clear Board With Thinner But Same Problem .Have Write Firm 4.6 But After This Only On Led Red Any One Have Solution ???? Here Picture = http://i52.tinypic.com
-
Log out botton in webpages doesn't work
When I log into a secure site and I want to log out the button doesn't work. I have to close the browser to log out. This occurred after I installed the new version 8.0. What is the problem? Should I go back to the previous version?
-
Whenever I go to open itunes this happens can someone help me? it says "This version of iTunes has not been correctly localized for this language. please run the English version." ?