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.

Similar Messages

  • Can't Send Attachments Using Exchange Account

    For some reason I can't send attachments using my Exchange account on my iPhone. Pictures, Word docs, Excel Docs, doesn't matter. They just get stuck in my out box and I get the following message, "Cannot Send Mail - An error occurred while delivering this message." I can receive attachments just fine, but cannot send or forward them. If I use any of the other email accounts on my phone, it works fine. The Exchange account is the only issue. Is this some limitation with Exchange on an iPhone or something? Anyone ever have the same problem as was able to fix it? Thanks!

    I've got 38 iPhones deployed running the 3.1.2 OS against an Exchange 2007 server. Several of my users complain about the same issue, and I've seen it myself. I have found a workaround of sorts - I've found that if I've sent a message with an attachment and I get a failure to send, if I manually browse down to the Sent Items folder, that forces a replication of the Sent Items. The next time I do a manual sync, the e-mail with the attachment will go.
    I presume this has something to do with Exchange trying to put a copy of the e-mail in to your Sent Items at the same time the iPhone is trying to send the message.
    Potentially, this might be solved by turning off the option to always store your sent e-mails in the Sent Items. I have not yet tested that as a workaround as from a corporate standpoint and an ease-of-use standpoint, we want that e-mail in the Sent Items for reference.
    If anyone has any success with this fix, please let me know.

  • Sending Attachments using Oracle Alerts

    Hi All,
    I am working on Oracle Alerts. I have to send an output of the report to the client, is it possible to send using Oracle Alerts.
    Thanks in Advance,
    Venky.

    Hi,
    To send attachments using Oracle Alert, you can follow below mentioned steps:
    1) While defining Oracle alert Action, Select 'Action Level' as 'Summary'
    2) In Action Details, select 'Action Type' as 'Operating System Script'
    3) Select 'Text' radio button
    4) Write following code : uuencode <Name of the file along with the path> <Name of the attachment in the mail>|mailx -c &cc_mail_id,&to_mail_id -s "<Subject of the Mailer>" &to_mail_id.
    5) You can use mail or sendmail command also instead of mailx command.
    6) Save Alert details
    Thanks and regards,
    Indira

  • How to send attachments using HTTP Binding Adapter?

    How to send attachments using HTTP Binding Adapter in Jdeveloper?
    Requirement: I need to send attachments to a system which can communicate with the middleware using https only.
    Kindly suggest..
    Edited by: Richa Juneja on Jan 28, 2013 4:03 AM

    Hi,
    Following links may help U
    /people/siva.maranani/blog/2005/09/03/invoke-webservices-using-sapxi
    http://help.sap.com/saphelp_nw04/helpdata/en/3c/b4a6490a08cd41a8c91759c3d2f401/content.htm
    http://help.sap.com/saphelp_nw04/helpdata/en/29/5bd93f130f9215e10000000a155106/frameset.htm
    to know the basics about soap adapter u cn check out this link
    /people/padmankumar.sahoo/blog/2005/02/15/an-overview-of-soap
    to get in detail about the attachments chk out this link
    hi i am unable to attach an attachment in File to mail scenario
    Regards
    Pullarao

  • Send mail with no sender address using Javamail

    I'm trying to send emails using javamail, it works fine but I would like to send emails with no sender address. When I don't set :
    message.setFrom(new InternetAddress("[email protected]"));
    or do just
    message.setFrom()
    I get my_user_name@my_machine_name as the sender address when i recieve the email.
    I understand the security problems about sending emails without sender but i need to automate the sending of confirmation messages that recievers can't answer to.
    Quentin.

    I get a lot of e-mail newsletters that say at the bottom "Please do not reply to this, nobody will read your reply". What's wrong with that? Set up an address and automatically purge any messages sent to it on a regular basis.
    Or if you want a different way to annoy people, use an address that doesn't exist on your server. Then people get a bounce message when they reply to it.
    You might also want to evaluate commonly-used spam filters and see if they filter out messages that don't have from-addresses. No point sending people messages if they get filtered out.

  • 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.
    Thanks

    Isnt there any way setup SMTP server on own pc?? I just want to send mails in my local area network.

  • Delivery Receipt After Sending Mail Using JavaMail ?

    Hi Friends,
    I have written an application using JavaMail which would be used to send mail
    using my organisation's SMTP Server.I would like to include the following functionality in it.Just as
    Microsoft's Outlook has an option to get Delivery Receipt of the mail and Read Receipt of the mail sent
    (Provided the email Client supports it) i would like to have a similar option in my application to.I would like to of how i can do it using JavaMail.I heard that basically we need to set some SMTP properties which the Mail Transfer Agent would recognize and send us the Delivery and Read Receipts.But,i am not sure of what those properties.Can anyone help me regarding this ?

    You might look into creating a custom header that provides a return reciept to the email address you specify. I'm not 100% sure that all mail servers support this but you might want to look into it as a solution.
    -Dave

  • 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.

  • Gettting attachments using JAVAMAIL

    Hi,
    I am dealing with an application which wants me to go through the mailbox and get the attachments of specific emails. These attachments are of different kinds. The attachments can vary from being rtf document, to Word, html, fo.. documents.. I got this skeleton code from the tutorial but dont know what to fill in..
    if (disposition == null) {
    // Check if plain
    MimeBodyPart mbp = (MimeBodyPart)part;
    if (mbp.isMimeType("text/plain")) {
    // Handle plain
    } else {
    // Special non-attachment cases here of
    // image/gif, text/html, ...
    What is it meant by handling plain? How do i handle html, worf, rtf documents.. Thanks a lot in advance.. Thanks
    Abhishek

    Try this as a reference. It works PERFECTLY. Ignore the comments.
    //If the content is ATTACHMENT
    filename = part.getFileName();
    if (filename != null) {
    filename = filename.trim();
    if(filename.equalsIgnoreCase(fileNameDownload.trim())) {
                                            //System.out.println("Downloading DOWN 1");
                                            session_id = this.DL_sessionid;
                                            directory = ATTACHMENTPath + m_user + "_" + session_id + "/";
                                            if(download) {
                                                 pushFile(part.getFileName(),part.getInputStream(),resp);
                                            } else {
                                                 saveFile(part.getFileName(), directory, part.getInputStream(), resp);
                                       filectr++;
         private void saveFile(String fileName, String Directory, InputStream input, HttpServletResponse resp)
              String myfile="";
              try
                   //Correct the file name;
                   String p_filename = javaFileParser(fileName);
                   File newDir = new File(Directory);
                   //Check if the directory does not exists!
                   if(!newDir.exists()) { //If it doesn't..
                        //Create the directory
                        newDir.mkdir();
                   String complete_path = Directory + p_filename;
                   File myFile=new File(complete_path);
                   //Check if a filename like this already exists!
                   if(myFile.exists()) {
                        //If it does..
                        //delete the current file residing into the directory
                        myFile.delete();
                   //Write the file (START)
                   FileOutputStream fos = new FileOutputStream(myFile);
                   BufferedOutputStream bos = new BufferedOutputStream(fos);
                   BufferedInputStream bis = new BufferedInputStream(input);
                   int aByte;
                   while ((aByte = bis.read()) != -1)
                   bos.write(aByte);
                   bos.flush();
                   bos.close();
                   bis.close();
                   //(END)
              catch (Exception x)
                   System.out.println("Error : " + x);
         private void pushFile(String fileName,InputStream input, HttpServletResponse resp)
              try
                   //Download the file to the Client's machine
                   ServletOutputStream stream = resp.getOutputStream();
                   resp.setContentType("application/octet-stream");
                   resp.setHeader("Content-Disposition","attachment;filename="+fileName.trim()+";");
                   //BufferedInputStream fif = new BufferedInputStream(new FileInputStream(complete_path));
                   BufferedInputStream fif = new BufferedInputStream(input);
                   int data;
                   while((data = fif.read()) != -1)
                   stream.write(data);
                   stream.flush();
                   fif.close();
                   stream.close();
              catch (Exception x)
                   System.out.println("Error : " + x);
         private String javaFileParser(String filename)
              //System.out.println("In EmailObject javaFileParser");
              String n_filename="";
              //Check if the file starts with '=?iso8859'
              //If it does, it will need parsing
              if(filename.startsWith("=?iso")) {
                   n_filename = filename.substring(15,filename.lastIndexOf("?"));
              } else
                   n_filename = filename;
              return n_filename;
    I suggest don't use JavaMail.. It has BUGS on some other email type. If not in POP3 then in IMAP.. Specialy when it receives "Enriched" contents types. Better yet don't use Java. It has lots of Bugs.

  • Sending Attachments with JavaMail API

    I have an application where I need to develop a simple e-mail servlet where, from an HTML form, clients can enter their return email address and attach a file and send it to me. The jGuru short course said that when trying to send attachments via a servlet, the user must upload the attachment with the encoding type "multipart/form-data". If I remove the "enctype=multipart/form-data" statement, I can successfully send an email without an attachment. But when I add the statement, the servlet fails. Here is the HTML that I have been using, without success:
    <form enctype="multipart/form-data" action="../servlets/TestEmail" method="post">
    From: <input type="text" name="from" value=""><br>
    Subject: <input type="text" name="subject" value=""><br>
    File to Attach: <input type="file" name="filename"><br>
    Message: <textarea name="message"></textarea><br><br>
    <input type="submit" value="Send">
    </form>
    Can anyone show me the error of my ways?
    Many thanks.
    Chris

    Hi,
    You'll need to use the servlet attachment jar from http://www.servlet.com in your webserver library. Check out the site, it'll tell you what to do.
    I've also done an example servlet at http://www.salniere.com/WebTests/ServletMail which you can download and check out.
    good luck
    Kevin

  • Sending fax using javaMail

    Hi,
    Iam working on an assignment where I should be able to send a page via email or efax. Iam using JavaMail for email. Not sure what to do for the Fax.
    Someone help me.
    Thanks
    Jo

    I think you have to write thr protocol yourself for eFax just search for it and you will hopefully find som info how the protocol is built!
    .leonard

  • Unable to send attachments using Safari.

    Safari version is 1.3.1. This is my first post. Have been using Mac's since 1990. Safari gives me an error message each time I try to send attachments , no matter the kind of attachment. Error message is: "Your previous operation was not successful, please try again." When I type the message, follow the attachment instructions and click to send, the message disappears for seconds and then comes back on screen with the error message in red.
    This has been going on for months. I am forced to use some other software to send messages with attachments. Any suggestions? I have checked the discussion boards and Apple support, also have reported bug to Apple, no answers.

    Hi Yang,
    I followed your instructions. It made no difference. I emptied my cache. The folder is not locked and I do have 'write' permission.
    Now for the embarrasing part of this. I may be blaming the wrong software. I open my computer with Safari, then go to Email and More in Verizon to send messages. Verizon is our DSL provider.
    Thanks for your help. I have been reading these discussions for some time and noticed that you frequently respond to questions.
    Pat

  • How to send attachments using java application and outlook

    Hi ,
    I created an application in java which is as
    on the Conference Tab i can schedule a conference and with the send command on page it map all the scheduled data to outlook(with all conference details) and using outlook send option the mails are send to appropriate user.
    but now i want to modify this application such as when i use the send command from my jsp page it should attach the file that is in .vcs or .ics format for auto updation of user calender.
    can any one know how to send attachment using java application .

    Last time I checked, SMS was a service between carriers and doing SMS yourself was really tricky. Some services existed to let you do it but as I recall they wanted non-trivial money.
    However, most phone carriers provide an email-to-SMS bridge of some kind.
    So the easiest thing is just to send an email.
    That's sending from a non-phone to a phone. There's a J2ME library to send/receive SMS from/to a phone.
    However, this is from memory, and a little out of date, so I could be entirely wrong. Hope it helps anyway.

  • Parsing email attachments using Javamail

    Hi All,
    I'm working on a multimedia application where I have to parse emails using Javamail.
    Here is a problem that i'm facing.
    When i'm receiving an attachment from icloud.com, i'm not able to get the filename whereas i'm able to get the fileSize and fileContent.
    I'm using Part.getFileName() to get the file name. and Part.getFileSize() and Part.getInputStream() to get size and the content.
    When i checked the attachment header, I could see the name encoded in ISO-8859-1.
    --Boundary_(ID_kS5Ng+OB35IVBfC+scPoMA)
    Content-id:[email protected]
    Content-type:image/jpeg;
    name*1*=utf-8"%20%32%33%30%32%32%30%31%33%37%32%35;
    name*2*=%2E%6A%70%67
    Content-transfer-encoding:BASE64
    Content-disposition:inline;
    filename*1*=utf-8"%20%32%33%30%32%32%%30%32%33%37%32%35
    filename*2*=%2E%6A%70%67
    In both the cases above, Part.getFileName() is returning null.
    I set the parameter mail.mime.decodeparameters="true".Still it is not working.
    It would be great if someone can suggest a solution for this.
    Thanks
    Shyama

    Just adding to the problem description:
    --Boundary_(ID_kzWHPgILjZtH2UtdriatGg)
    Content-id: <[email protected]>
    Content-type: image/jpeg; name*1*=ISO-8859-1''%32%2E%6A%70%67
    Content-transfer-encoding: BASE64
    Content-disposition: inline; filename*1*=ISO-8859-1''%32%2E%6A%70%67
    This is the header which could see in another mail.

  • 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

Maybe you are looking for

  • Can we email more than one photo at once from the iPad?

    It is easy to email a photo from the iPad, one photo at a time, but is it possible to send multiple photos attached to one email from the iPad?

  • Nokia maps 1.0 - india maps, Maharashtra and Goa

    Hi all,  I want to download india maps and specifically maps of Maharashtra and Goa. I bought a Nokia C2-03 (dual-sim) recently and have been trying to download maps via Nokia Ovi Suite 3.1.1.90 but it has been a failure.  The device itself does not

  • Is it possible to sort PS layers by mean RGB value?

    I am trying to figure out a way to sort layers in a PS file by mean RGB value (in other words, on a scale from light to dark).  Is this possible?  I know that one can stack files into layers, so another approach to doing what I want would be by sorti

  • Compliance Calibrator analysing APO

    Hi, I've installed CC4.0 in a 46C release, we would like to run RA against APO transactions, but I can't establish a correct RFC connection without receiving an ABAP error... Can you help on the config? Thanks very much, Enrico

  • Safari will not recognize Java while firefox does???

    At some point a few weeks ago Safari stopped recognizing Java.  I can use Java if i go thru Firefox but not in safari.  Any ideas why?