Sendmail vs JavaMail

Hi,
I intend to start writing a mailing list / newsletter management system, but I'm having trouble deciding if I should use JavaMail to do the actual mailing or if I should connect to a MTA (mail server) to do the mailing. My MTA of choice would be Sendmail. Does anyone have any opinions on which would be more efficient? faster? reliable?
How would you approach things if you wanted to handle very large mailing lists (50 000 - 100 000 subscribers)? Could JavaMail handle it?
Does anyone know of any existing high quality, open source mailing list systems that I could just build a front end for? Something that uses a SQL database for storage would be preferable.
I'd really appreciate any suggestions anyone might have. I'll probably have to go run up my VISA card at O'Reilly's website too. Oh darn :-)

I am struggling to find an effective way to send email from my Unix/Servlet program.
I have seen many scripts on the web, both Java/Perl, both sendmail/SMTP with sockets.
Any implementation in Java fails.
I can only execute Java as a Servlet and the HTML page is returned, but no mail is sent.
Conversely, all my Perl scripts work fine.
One thing that has worked is Runtime.exec("..../cgi-bin/email.pl"); // but does Not work with args
My ancient (sometimes aggravating) environment is:
Unix, JDK1.1.7, ApacheJServ 1.1.1
I have no access to the Shell or the JServ logs, so debugging is quite difficult.
Often, I have used RandomAccessFile as a debugging log file.
JavaMail is not available, nor can I get the jar added to the classpath.
Some basics:
Does sendmail use SMTP sockets underneath ?
Using SMTP, is there some kind of authorization issue ? alias req'd ?
Does sendmail also require that you end the message body with a "." ? (No -is my guess)
Are there good ways to debug this ?
Is there a blocking issue, calling perl ? (Solution: use AutoFlush ? )
What is best Runtime.exec() System.exec() ?
How to best pass arguments ? If I started a new shell process (sh), I would use quoting rules.
I've seen the fancier style of Runtime.exec(String[] {"/usr/bin/sh", ".../my_perl.pl", "arg1"});
But I haven't gotten this to work yet.
joshman: I like the directory solution, because it sounds fairly clean (call shell script/ for each)
I could create 1file/Email with the Headers and Body, then loop thru. Maybe even have a Java thread kick off the script.
Is cron too much to ask for on my host ?
LordMJ: I asked on Google, but got no response. Is there a way I can pull out the classes from mail.jar and install them into JServ ? (in the correct packages, of course)
TIA for your suggestions

Similar Messages

  • Configuring JavaMail with Sendmail

    Hi there,
    I create a simple standalone app that has the following method in it for sending emails:
      String SMTPServerName = "smtp.someserver.com";
      String addressTo = "[email protected]";
      public boolean sendMail(String addressTo)
        try
           Properties props = System.getProperties();
           props.put("mail.smtp.host", SMTPServerName);
           session = Session.getDefaultInstance(props, null);
           MimeMessage msg = new MimeMessage(session);
           msg.setRecipients(Message.RecipientType.TO,
           InternetAddress.parse(addressTo, false));
           msg.setFrom(new InternetAddress(from_field.getText()));
           msg.setSubject(subject_field.getText());
           //msg.setText(message);
           if(plainText.isSelected())
              msg.setContent(textarea.getText(), "text/plain");
           else
              msg.setContent(textarea.getText(), "text/html");
           msg.setHeader("X-Mailer", mailer);
           msg.setSentDate(new Date());
           Transport.send(msg);
        catch (MessagingException e)
          //System.out.println("SMTPServerName: " + SMTPServerName);
          //response 421 just means the SMTP server was unavailable
          if(e.getMessage().indexOf("421") != -1)
             JOptionPane.showMessageDialog(this, "MessagingException - SMTP Server unavailable.", "Message", JOptionPane.PLAIN_MESSAGE);
          else
             e.printStackTrace();
          return false;
        return true;  
      }This method works perfectly if the SMTPServerName is set for my ISP's smtp server. But since I have my own in-house server now which is running Linux, I thought to try and make use of its Sendmail server instead.
    So, I need to know what I need to change in my method, if anything, in order to send out emails through Sendmail. For starters, I consulted a book I have on linux which explains how to configure Sendmail as a relay to send messages out. I made those changes and restarted Sendmail. So that end is set.
    Since the server is part of my LAN on IP address: 192.168.2.119, In my client app (on a different Windows computer withing the LAN), I tried setting the SMTPServerName to the IP address of my server running Sendmail. Then proceeded to send myself an email. That didn't work. I know Sendmail is listening on port 25 so I tried 192.168.2.119:25 adding the port number, but that didn't work.
    So, what is SMTPServerName supposed to be if I'm trying to connect to Sendmail to send out an email?
    Is the method adequate for what I need it to do, or do I have to change it?
    Alan

    The mail.smtp.host property should be set to the DNS host name for your
    mail server. If your mail server doesn't have a DNS host name, it's probably
    going to run into other problems relay messages to other internet hosts.
    Still, you should be able to set the property to the IP address of the server.
    If that's still not working, read the JavaMail FAQ, which has many tips on
    debugging such problems.

  • Error with OCI8 driver installing sendmail/javamail

    Hi to All,
    From Dos window I run the command:
    loadjava -user sys/pwd@name_db -resolve -synonym activation.jar
    This is the first step in order to install a Sendmail package based on javamail, but I have this error:
    =============================
    Java.exe error
    Impossible to find the enterpoint kpufhndl0 of procedure in the library of dynamic link OCI.dll (Sorry, this is a translation of italian language)
    OK
    =============================
    After I click on OK and this is the next response:
    Error while connecting with OCI8 driver to namedb:oracle.aurora.server.tools.loadjava.ToolsException: The JDBC OCI8 Driver is not installed properly, use -thin to try the JDBC Thin Driver: C:\oracle\product\10.2.0\oradb10g\BIN\ocijdbc10.dll: Impossible to find the specified procedure.
    exiting: could not open connection
    After, I have used the command:
    loadjava -thin C:\oracle\product\10.2.0\oradb10g\BIN\ocijdbc10.dll
    This is the result:
    SQL error while connecting with driver to default database: Listener refused the connection with the following error:
    ORA-12505, TNS: listener does not currently know of SID given in connect descriptor
    The connection descriptor used by the client was:
    localhost:1521: orcl
    exiting: could not open connection
    But the connection descriptor that I use is eg COSFI, not orcl.
    Other applications works fine with my descriptor.
    Someone can help me in order to resolve this problem ?
    Thank You and Best Regards.
    Gaetano
    Message was edited by:
    NICK048

    Gaetano,
    I see you took my advice when I replied to your Error with OCI8 driver installing sendmail/javamail.
    However, it doesn't look like you studied the Oracle documentation for loadjava because the command you posted doesn't look right at all.
    Please refer to the Java Developer's Guide for the correct syntax and usage of the loadjava command.
    Good Luck,
    Avi.

  • JavaMail code bug or Solaris sendmail problem?

    Hi all,
    i write a java app to send out the email using SMTP sendmail.
    I set the a list of emails (yahoo, gmail, hotmail, lotus notes etc) into BCC field only and left the To Field and CC Field empty.
    Then i set the subject and the email content and send out the emails.
    Here are the 2 scenarios happened based on different SMTP server:
    1. using Ms Exchange Server
    as expected, the email recepients see the To and CC field empty, and no other email addresses can be seen from the email. this behaviour is consistent for all email clients.
    2. using solaris sendmail
    using same java code, different behaviours encountered depended on the email clients:
    a) using yahoo, gmail... all bcc list emails are displayed in To Field!!
    b) using lotus note ...displayed 1 email address (get from BCC list) makes it look like a spam!
    c) using hotmail and Ms Outlook 2003, no issue, To and CC field are empty, and no email addresses are exposed.
    Can any java experts please advise what is actually happening here?
    To be thorough, i will attach my java code that send out the email here :)
    Thanks!!!!
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    import java.util.Properties;
    import java.util.PropertyResourceBundle;
    import java.util.ResourceBundle;
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;
    import javax.sql.DataSource;
    import org.apache.commons.dbcp.BasicDataSource;
    public class EmailBlaster {
         private final String SQL = "my_sql_statement here" +
         public final String PROPERTIES_FILE = "emailblaster"; //my prop file
         private ResourceBundle props;
         private BasicDataSource sourceDs;
         private ResourceBundle getProps() {
              if (props==null) {
                   props = PropertyResourceBundle.getBundle(PROPERTIES_FILE);
              return props;
         private void resetProps() {
              props = null;
         public void sendEmail() {
              String msg = getMsg();
              List recipients = new ArrayList();
              recipients.add("[email protected]");
              recipients.add("[email protected]");
              recipients.add("anyMsOulookBasedEmail@Xxxxxxxx");
              recipients.add("[email protected]");
              String sender = getProps().getString("email.sender");
                   try {
                        postMail(list, sender, msg);
                   } catch (Exception ex) {
                        System.out.println("Error while sending report email|ex: " + ex.getMessage());
                        ex.printStackTrace();
         public static void main (String [] args) {
              EmailBlaster obj = new EmailBlaster();
              System.out.println("Start emailing -- " + new Date());
              obj.sendEmail();
              System.out.println("Done -- " + new Date());
              obj.resetProps();
         * This code copy from ReportGenerator.java
         * @param recipients
         * @param from
         * @param attachments
         * @throws MessagingException
    private void postMail(List recipients, String from, String msg) throws MessagingException
    boolean debug = false;
    //Set the host smtp address
    Properties props = new Properties();
    String incomingServer = getProps().getString("email.smtp.incoming.server");
    String outgoingServer = getProps().getString("email.smtp.outgoing.server");//i test use MsExchange Server and SendMail Solaris
    props.put(incomingServer, outgoingServer);
    // create some properties and get the default Session
    Session session = Session.getDefaultInstance(props, null);
    session.setDebug(debug);
    //Define message
    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    InternetAddress[] addressTo = new InternetAddress[recipients.size()];
    for (int i = 0; i < recipients.size(); i++)
    addressTo[i] = new InternetAddress((String)recipients.get(i));
    message.setRecipients(Message.RecipientType.BCC, addressTo);
    message.setSubject(getProps().getString("email.subject"));
    message.setContent(msg, "text/html");
    Transport.send(message);
         private String getMsg() {
              String msg="";
              msg = getProps().getString("email.msg");
              return msg;
    }

    Hi bshannon
    Thanks for the reply :)
    there was an accident happened that exposed the users' email addresses using the above java code and sendmail. that is, our code pull a list of users' email addresses, put it into BCC list, and left TO and CC list empty, and then send it using sendmail as SMTP
    probably I didnt make myself clear :)
    the most important thing now is to understand why the above scenario happen based on the above java code and sendmail SMTP. my head will be rolling down the road if I cant find any satisfy explanation ^_^"
    any kind soul that can help to run/test the similar code as above in other SMTP servers (especially sendmail solaris smtp) will be highly regarded
    Thanks!

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

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

    Hi 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

  • Attachment Problem in JavaMail API

    Can anybody help me...
    when 'm trying to attach a file to a mailing aplication(sending attachment),
    an flurry of exceptions are occuring...
    'm using win98 and JDK1.4
    here is the code..can anybody provide a viable solution that works?
    thanks in advance
    * main1.java
    * Created on August 20, 2002, 2:55 PM
    * @author Shamik Ghosh
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import java.net.*;
    import java.io.*;
    import java.util.Properties;
    import javax.mail.*;
    import javax.mail.internet.*;
    import javax.activation.*;
    public class main1 extends javax.swing.JFrame implements ActionListener,ItemListener {
    JMenuBar mbar;
    JMenu file,other,help;
    JMenuItem open,save,read_mail;
    JFrame frame_f;
    FileReader fr;
    BufferedReader br;
    boolean check;
    String from_m,smtp_m,from_m1,smtp_m1,result,
    s1,s2,from_server,from_host,to_file,which_file,attach_text;
    File f;
    /** Creates new form main1 */
    public main1() {
    initComponents();
    setSize(550,500);
    setResizable(false);
    // ------------------------centering the display
    int width=550; // note that "width" & "height" are keywords and
    int height=500; // JAVA defined variables.
    Dimension screen=Toolkit.getDefaultToolkit().getScreenSize();
    int x=(screen.width-width)/2;
    int y=(screen.height-height)/2;
    setBounds(x,y,width,height);
    try{
    fr=new FileReader("address.txt");
    br=new BufferedReader(fr);
    String s;
    while((s=br.readLine()) !=null)
    {jComboBox1.addItem(s);}
    fr.close();
    }catch(Exception e){ System.out.println(e);}
    check_info();//calling the method to check the info
    //jTextField1.setText(from_m);
    //jTextField3.setText(smtp_m);
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    private void initComponents() {//GEN-BEGIN:initComponents
    buttonGroup1 = new javax.swing.ButtonGroup();
    buttonGroup2 = new javax.swing.ButtonGroup();
    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    jTextField1 = new javax.swing.JTextField();
    jTextField2 = new javax.swing.JTextField();
    jLabel3 = new javax.swing.JLabel();
    jTextField3 = new javax.swing.JTextField();
    jComboBox1 = new javax.swing.JComboBox();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jButton3 = new javax.swing.JButton();
    jLabel4 = new javax.swing.JLabel();
    jRadioButton3 = new javax.swing.JRadioButton();
    jRadioButton4 = new javax.swing.JRadioButton();
    jButton4 = new javax.swing.JButton();
    jButton6 = new javax.swing.JButton();
    jButton5 = new javax.swing.JButton();
    jTextField4 = new javax.swing.JTextField();
    jLabel5 = new javax.swing.JLabel();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTextArea1 = new javax.swing.JTextArea();
    jScrollPane2 = new javax.swing.JScrollPane();
    jTextArea2 = new javax.swing.JTextArea();
    jLabel6 = new javax.swing.JLabel();
    jLabel7 = new javax.swing.JLabel();
    jLabel8 = new javax.swing.JLabel();
    jLabel9 = new javax.swing.JLabel();
    jLabel10 = new javax.swing.JLabel();
    //actionlisteners
    jButton1.addActionListener(this);
    jButton2.addActionListener(this);
    jButton3.addActionListener(this);
    jButton4.addActionListener(this);
    jButton5.addActionListener(this);
    jButton6.addActionListener(this);
    mbar=new JMenuBar();
    setJMenuBar(mbar);
    file=new JMenu("File");
    other=new JMenu("Other");
    help=new JMenu("Help");
    mbar.add(file);
    mbar.add(other);
    mbar.add(help);
    getContentPane().setLayout(null);
    setTitle("MailMan :Designed and Programmed by Shamik Ghosh");
    //setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowClosing(java.awt.event.WindowEvent evt) {
    exitForm(evt);
    jLabel1.setText("From:");
    getContentPane().add(jLabel1);
    jLabel1.setBounds(30, 20, 32, 17);
    jLabel2.setText("To:");
    getContentPane().add(jLabel2);
    jLabel2.setBounds(30, 60, 17, 17);
    getContentPane().add(jTextField1);
    jTextField1.setBounds(110, 20, 240, 21);
    getContentPane().add(jTextField2);
    jTextField2.setBounds(110, 60, 240, 21);
    jLabel3.setText("Smtp Server:");
    getContentPane().add(jLabel3);
    jLabel3.setBounds(10, 100, 74, 17);
    getContentPane().add(jTextField3);
    jTextField3.setBounds(110, 100, 240, 21);
    jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] {  }));
    jComboBox1.setToolTipText("Mail Addresses");
    jComboBox1.setAutoscrolls(true);
    jComboBox1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jComboBox1ActionPerformed(evt);
    getContentPane().add(jComboBox1);
    jComboBox1.setBounds(110, 150, 240, 20);
    jComboBox1.setFont(new java.awt.Font("Abadi MT Condensed Light", 1, 12));
    jButton1.setToolTipText("Send the message you have typed");
    jButton1.setMnemonic('m');
    jButton1.setFont(new java.awt.Font("Abadi MT Condensed Light", 1, 12));
    jButton1.setText("Send Mail");
    getContentPane().add(jButton1);
    jButton1.setBounds(370, 300, 160, 25);
    //jButton2.setFont(new java.awt.Font("Abadi MT Condensed Light", 0, 12));
    jButton2.setText("Save Info");
    jButton2.setToolTipText("Save Settings for more mails");
    jButton2.setMnemonic('I');
    getContentPane().add(jButton2);
    jButton2.setBounds(370, 340, 160, 25);
    jButton3.setText("Clear ");
    jButton3.setMnemonic('C');
    jButton3.setToolTipText("Clear all text");
    getContentPane().add(jButton3);
    jButton3.setBounds(370, 380, 160, 27);
    jLabel4.setText("Your Contact Addresses");
    jLabel4.setFont(new java.awt.Font("Arial Narrow", 0, 12));
    getContentPane().add(jLabel4);
    jLabel4.setBounds(110, 130, 200, 15);
    jRadioButton3.setText("Use Log File");
    jRadioButton3.setMnemonic('L');
    getContentPane().add(jRadioButton3);
    jRadioButton3.setBounds(260, 310, 90, 25);
    jRadioButton4.setText("No Log File");
    //jRadioButton4.setMnemonic('N');
    //getContentPane().add(jRadioButton4);
    //jRadioButton4.setBounds(260, 340, 86, 25);
    jButton4.setText("Undo Info");
    jButton4.setMnemonic('U');
    jButton4.setToolTipText("Undo settings");
    getContentPane().add(jButton4);
    jButton4.setBounds(260, 380, 87, 27);
    getContentPane().add(jTextField4);
    jTextField4.setBounds(20, 380, 210, 21);
    jLabel5.setText("Attachment");
    jLabel5.setFont(new java.awt.Font("Abadi MT Condensed Light", 1, 12));
    getContentPane().add(jLabel5);
    jLabel5.setBounds(70, 360, 70, 15);
    jButton5.setFont(new java.awt.Font("Abadi MT Condensed Light", 1, 12));
    jButton5.setText("Browse");
    jButton5.setMnemonic('B');
    jButton5.setToolTipText("Browse files for Attachment");
    getContentPane().add(jButton5);
    jButton5.setBounds(150, 350, 80, 25);
    jButton6.setText("Attach & Send");
    jButton6.setMnemonic('A');
    jButton6.setToolTipText("Attach File & Send Mail");
    getContentPane().add(jButton6);
    jButton6.setBounds(260, 340, 86, 25);
    jScrollPane1.setViewportView(jTextArea1);
    getContentPane().add(jScrollPane1);
    jScrollPane1.setBounds(370, 20, 160, 270);
    jLabel10.setText("Type your mail:");
    jLabel10.setFont(new java.awt.Font("Abadi MT Condensed Light", 1, 12));
    getContentPane().add(jLabel10);
    jLabel10.setBounds(370, 5, 125, 10);
    jScrollPane2.setViewportView(jTextArea2);
    getContentPane().add(jScrollPane2);
    jScrollPane2.setBounds(20, 200, 340, 90);
    jLabel6.setText("(your ISP smtp)");
    jLabel6.setFont(new java.awt.Font("Abadi MT Condensed Light", 0, 10));
    getContentPane().add(jLabel6);
    jLabel6.setBounds(10, 120, 70, 12);
    jLabel7.setText("porgrammed and designed by : Shamik Ghosh");
    jLabel7.setFont(new java.awt.Font("Abadi MT Condensed Light", 0, 10));
    getContentPane().add(jLabel7);
    jLabel7.setBounds(260, 410, 160, 12);
    jLabel8.setText("[email protected]");
    jLabel8.setFont(new java.awt.Font("Abadi MT Condensed Light", 0, 10));
    getContentPane().add(jLabel8);
    jLabel8.setBounds(420, 410, 80, 12);
    jLabel9.setText("Msg.for the Mail Sent:");
    jLabel9.setForeground(java.awt.Color.black);
    jLabel9.setFont(new java.awt.Font("Abadi MT Condensed Light", 0, 10));
    getContentPane().add(jLabel9);
    jLabel9.setBounds(20, 180, 80, 12);
    file.add(open=new JMenuItem("Open"));
    open.setAccelerator(KeyStroke.getKeyStroke('O',Event.CTRL_MASK,true));
    file.addSeparator();
    file.add(save=new JMenuItem("Save"));
    save.setAccelerator(KeyStroke.getKeyStroke('S',Event.CTRL_MASK,true));
    file.addSeparator();
    other.add(read_mail=new JMenuItem("Add Address"));
    read_mail.setAccelerator(KeyStroke.getKeyStroke('A',Event.CTRL_MASK,true));
    other.addSeparator();
    //adding actionListener to menuitems
    open.addActionListener(this);
    save.addActionListener(this);
    read_mail.addActionListener(this);
    jComboBox1.addItemListener(this);
    pack();
    }//GEN-END:initComponents
    public void itemStateChanged(ItemEvent ie)
    String add_list;
    add_list=String.valueOf(jComboBox1.getSelectedItem());
    jTextField2.setText(add_list);
    } // for item event source
    public void actionPerformed(ActionEvent ae)
    if(ae.getSource()==jButton1)
    if(ae.getSource()==jButton1) {
    SwingUtilities.invokeLater(new Runnable()
    {  public void run()
    sendMail();
    if(ae.getSource()==jButton2) //save info
    from_m =jTextField1.getText();
    smtp_m =jTextField3.getText();
    from_m1 =from_m+"\n";
    smtp_m1 =jTextField3.getText();
    result =from_m1+smtp_m1;
    try{
    byte buf[]=result.getBytes();
    OutputStream fo=new FileOutputStream("info.txt");
    for(int i=0;i<buf.length; i++ )
    fo.write(buf);
    fo.close();
    }catch(Exception e){ System.out.println(e);}
    jTextField1.setEditable(false);
    jTextField3.setEditable(false);
    if(ae.getSource()==jButton3) //clear
    jTextArea1.setText(" ");
    jTextArea2.setText(" ");
    if(ae.getSource()==jButton4)//undo info
    jTextField1.setEditable(true);
    jTextField3.setEditable(true);
    if(ae.getSource()==jButton5)//browse for attachment
    try {
    FileDialog file = new FileDialog (main1.this, "Load File", FileDialog.LOAD);
    file.setFile ("*.*"); // Set initial filename filter
    file.show(); // Blocks
    String curFile;
    if ((curFile = file.getFile()) != null) {
    String filename = file.getDirectory() + curFile;
    char[] data;
    setCursor (Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    f = new File (filename);
    try {
    System.out.println("INSIDE TRY");
    FileReader fin = new FileReader (f);
    int filesize = (int)f.length();
    data = new char[filesize];
    fin.read (data, 0, filesize);
    setCursor (Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    } catch (Exception exc) {}
    jTextField4.setText(filename);
    } catch(Exception e){}
    if(ae.getSource()==jButton6)//send attachment & Mail
    try{
    sendmail2();
    }catch(Exception e){}
    if(ae.getSource()==open)//menu open
    if(ae.getSource()==save)//menu save
    if(ae.getSource()==read_mail)//menu read_mail
    address_add();
    } //actionperformed
    public void sendmail2()
    try {
    //which_file,attach_text
    from_server=jTextField3.getText();
    from_host=jTextField1.getText();
    to_file=jTextField2.getText();
    which_file=jTextField4.getText();
    attach_text=jTextArea1.getText();
    //getting system property
    Properties props=System.getProperties();
    //setup mail server
    props.put("mail.smtp.host",from_server);
    //get session
    Session session=Session.getInstance(props,null);
    // Define message
    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from_host));
    message.addRecipient(Message.RecipientType.TO,
    new InternetAddress(to_file));
    message.setSubject("Hello JavaMail Attachment");
    //define message part
    BodyPart messageBodyPart=new MimeBodyPart();
    // Fill the message
    messageBodyPart.setText(attach_text);
    // Create a Multipart
    Multipart multipart = new MimeMultipart();
    // Add part one
    multipart.addBodyPart(messageBodyPart);
    //attaching**********************************secon Part Attachment
    //creating second body part
    messageBodyPart=new MimeBodyPart();
    DataSource source=new FileDataSource(which_file); //was filename
    //setting data handler to the attachment
    messageBodyPart.setDataHandler(new DataHandler(source));
    //setting the filename
    messageBodyPart.setFileName(which_file);
    //adding part two
    multipart.addBodyPart(messageBodyPart);
    //put parts in the message
    message.setContent(multipart);
    //Sending msg
    Transport.send(message);
    }catch(Exception e){}
    } //sendmail2
    public void address_add()
    addr=jTextField2.getText();
    str_addr=addr+"\n";
    //jComboBox1.addItem(" ");
    jComboBox1.addItem(addr);
    System.out.println("INSIDE WRITING METHOD");
    try{
    byte buf[]=str_addr.getBytes();
    OutputStream f0=new FileOutputStream("address.txt",true);
    for(int i=0;i<buf.length; i++ )
    f0.write(buf[i]);
    f0.close();
    }catch(Exception e){ System.out.println(e);}
    public void check_info()
    try{
    fr=new FileReader("info.txt");
    br=new BufferedReader(fr);
    while((s1=br.readLine()) !=null && (s2=br.readLine()) !=null)
    jTextField1.setText(s1);
    jTextField3.setText(s2);
    break;
    fr.close();
    }catch(Exception e){ System.out.println(e);}
    public void sendMail()
    {  try
    Socket s = new Socket(jTextField3.getText(), 25);
    out = new PrintWriter(s.getOutputStream());
    in = new BufferedReader(new
    InputStreamReader(s.getInputStream()));
    String hostName
    = InetAddress.getLocalHost().getHostName();
    send(null);
    send("Host " + hostName);
    send("Mail FROM: " + jTextField1.getText());
    send("Rcpt TO: " + jTextField2.getText());
    send("Data");
    out.println(jTextArea1.getText());
    send(".");
    s.close();
    catch (IOException exception)
    {  jTextArea2.append("Error: " + exception);
    String err="Message cannot be sent!"+"\n"
    +"Please verify the setting(s)."+
    "\n"+"Else there may be a NetWork Problem."+
    "\n"+"Please verify and Try Again.";
    JOptionPane.showMessageDialog(frame_f,err,"Message Transmission Failure",JOptionPane.ERROR_MESSAGE);
    public void send(String s) throws IOException
    {  if (s != null)
    {  jTextArea2.append(s + "\n");
    out.println(s);
    out.flush();
    String line;
    if ((line = in.readLine()) != null)
    jTextArea2.append(line + "\n");
    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
    // Add your handling code here:
    }//GEN-LAST:event_jComboBox1ActionPerformed
    /** Exit the Application */
    private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm
    System.exit(0);
    }//GEN-LAST:event_exitForm
    * @param args the command line arguments
    public static void main(String args[]) {
    new main1().show();
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.ButtonGroup buttonGroup2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JRadioButton jRadioButton3;
    private javax.swing.JRadioButton jRadioButton4;
    private javax.swing.JButton jButton4;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea jTextArea2;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JLabel jLabel10;
    private BufferedReader in;
    private PrintWriter out;
    private String addr,str_addr;
    // End of variables declaration//GEN-END:variables

    Hi I have this problem which I believe you can help me resolve:
    In my code, there are two lines:
    message.setContent(messageBody, "text/html"); // this sets body of message
    message.setContent(bodyPartObject); // this attaches a file
    but it turns out that the second "setContent" statement over-writes the first one, so that I get no message in the body of the mail.
    What can I do about it, shamik1? Thanks!

  • Sendmailjpkg.sendmail -  550 5.7.1 Unable to relay

    Hi to all,
    Oracle 10g database.
    We have an application that sends emails (only with one email address), with sendmailjpkg.sendmail,
    We've recently installed an exchange 2010 server, and in doing so we've changed the relevant DNS/MX records to point the to new IP address. I changed the new SMTP address in database (in sendmail Java class – props.setProperty (“mail.host”,”NEW SMTP IP”), ...) and everything was ok when we sent email to local domain users, but when database sent to external email users we get this error:
    javax.mail.SendFailedException: *550 5.7.1 Unable to relay*
    I know what is the problem is, exchange required full authenication to send emails outside the domain with JavaMail, attempt at stopping spam…
    But I do not know how to create authenticator class, how to put authentications in sendmail Java class or in my procedure where I use sendmailjpkg.sendmail, or anywhere else ?
    Thanks!

    Isn't that a Java issue rather than a SQL or PL/SQL issue?

  • JavaMail send 9M pdf attach through Gmail

    Hello Everyone,
    I have this issue while trying to send email with attach (an pdf of 9M) . In the beginning I can see in the console that packets are sent really fast. Everything seem OK, but in time the speed decrease, Thus in about 10 minutes or more it barely sends anything. No errors whatsoever.
    If I am sending smaller attachments (under 900K) they work fine, i receive them, open them...all is great.
    I performed this test, sending the same content with the same attach directly from gmail web mail and it was uploaded in about 10 minutes- which i find it acceptable. Why does JavaMail take so long?
    My application is a standalone app , a swing app. I tried sending the mail both from GUI's main thread and from a distinct thread. No big difference.
    Anyone any idea? Someone hit this issue before?
    Here is some code:
    Properties props = new Properties();
              props.put("mail.smtp.user", userName);
    props.put("mail.smtp.host", host);
    if(!"".equals(port))
    props.put("mail.smtp.port", port);
    //if(!"".equals(starttls))
    //props.put("mail.smtp.starttls.enable",starttls);
    props.put("mail.smtp.auth", auth);
    if(debug)
    props.put("mail.smtp.debug", "true");
    else
    props.put("mail.smtp.debug", "false");          
              if(!"".equals(port))
    props.put("mail.smtp.socketFactory.port", port);
              if(!"".equals(socketFactoryClass))
    props.put("mail.smtp.socketFactory.class",socketFactoryClass);
              //if(!"".equals(fallback))
    //props.put("mail.smtp.socketFactory.fallback", fallback);
    try
    Session session = Session.getDefaultInstance(props, null);
    session.setDebug(debug);
    MimeMessage msg = new MimeMessage(session);
    //msg.setText(text);
    msg.setSubject(subject);
    msg.setFrom(new InternetAddress("[email protected]"));
    for(int i=0;i<to.length;i++)
    msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    for(int i=0;i<cc.length;i++)
    msg.addRecipient(Message.RecipientType.CC, new InternetAddress(cc[i]));
    for(int i=0;i<bcc.length;i++)
    msg.addRecipient(Message.RecipientType.BCC, new InternetAddress(bcc[i]));
    // create the message part
    MimeBodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setText(text);
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);
    messageBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource("f:/__BOOKS__/1000_Java_Tips_low.pdf");
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName("1000_Java_Tips_low.pdf");
    messageBodyPart.setFileName(source.getName());
    //messageBodyPart.attachFile("f:/__BOOKS__/J2EE JSF Tutorial.pdf");
    multipart.addBodyPart(messageBodyPart);
    msg.setContent(multipart);
    msg.saveChanges();
    Transport transport = session.getTransport("smtp");
    transport.connect(host, userName, passWord);
    transport.sendMessage(msg, msg.getAllRecipients());
    transport.close();
    return true;
    Thanks and best regards,
    Ionut.

    Off course, i let the application run just to see it manage to send the mail. But after about an hour or more i get this error:
    GmItAHP6Wj1nblOEOurlwBQ1DEfXSmQPShOnSIN0mimP3+z9NI5wNEnVWNfvIUI1JXkagvIO8yvS
    java.net.SocketException: Connection reset by peer: socket write error
    at java.net.SocketOutputStream.socketWrite0(Native Method)
    at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
    at java.net.SocketOutputStream.write(SocketOutputStream.java:136)
    at com.sun.net.ssl.internal.ssl.OutputRecord.writeBuffer(OutputRecord.java:295)
    at com.sun.net.ssl.internal.ssl.OutputRecord.write(OutputRecord.java:284)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.writeRecordInternal(SSLSocketImpl.java:727)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:715)
    at com.sun.net.ssl.internal.ssl.AppOutputStream.write(AppOutputStream.java:59)
    at com.sun.mail.util.TraceOutputStream.write(TraceOutputStream.java:114)
    at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:65)
    at java.io.BufferedOutputStream.write(BufferedOutputStream.java:109)
    at com.sun.mail.util.CRLFOutputStream.write(CRLFOutputStream.java:84)
    at com.sun.mail.smtp.SMTPOutputStream.write(SMTPOutputStream.java:87)
    at com.sun.mail.util.CRLFOutputStream.write(CRLFOutputStream.java:75)
    at com.sun.mail.util.BASE64EncoderStream.write(BASE64EncoderStream.java:140)
    at javax.activation.DataHandler.writeTo(DataHandler.java:322)
    at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1403)
    at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:874)
    at javax.mail.internet.MimeMultipart.writeTo(MimeMultipart.java:444)
    at com.sun.mail.handlers.multipart_mixed.writeTo(multipart_mixed.java:102)
    at javax.activation.ObjectDataContentHandler.writeTo(DataHandler.java:897)
    at javax.activation.DataHandler.writeTo(DataHandler.java:330)
    at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1403)
    at javax.mail.internet.MimeMessage.writeTo(MimeMessage.java:1745)
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:636)
    at ro.crm.johnny.mail.Mailer.sendMail(Mailer.java:160)
    at ro.crm.johnny.mail.Mailer.sendit(Mailer.java:45)
    at ro.crm.johnny.MainFrame.cmdSendEmailActionPerformed(MainFrame.java:1306)
    at ro.crm.johnny.MainFrame.access$2100(MainFrame.java:65)
    at ro.crm.johnny.MainFrame$22.actionPerformed(MainFrame.java:811)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1849)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2169)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
    at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:231)
    at java.awt.Component.processMouseEvent(Component.java:5517)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3135)
    at java.awt.Component.processEvent(Component.java:5282)
    at java.awt.Container.processEvent(Container.java:1966)
    at java.awt.Component.dispatchEventImpl(Component.java:3984)
    at java.awt.Container.dispatchEventImpl(Container.java:2024)
    at java.awt.Component.dispatchEvent(Component.java:3819)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3892)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
    at java.awt.Container.dispatchEventImpl(Container.java:2010)
    at java.awt.Window.dispatchEventImpl(Window.java:1791)
    at java.awt.Component.dispatchEvent(Component.java:3819)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
    javax.mail.MessagingException: IOException while sending message;
    nested exception is:
    java.net.SocketException: Connection reset by peer: socket write error
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:676)
    at ro.crm.johnny.mail.Mailer.sendMail(Mailer.java:160)
    Anyone, Any idea yet?

  • JavaMail NoClassDefFoundError

    The following code complies OK but won't run. I get a ava.lang.NoClassDefFoundError: . What's my problem?
    import java.util.Properties;
    import javax.mail.*;
    import javax.mail.internet.*;
    public class SendMail {
    public static void main (String[] args) throws Exception {
    String host = "mail.xxxxx.com";
    String from = "[email protected]";
    Address address = new InternetAddress("[email protected]")
    Properties props = System.getProperties();
    props.put("mail.smtp.host", host);
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    message.setRecipients(Message.RecipientType.TO,
    address);
    message.setSubject("Hello JavaMail");
    message.setText("Welcome to JavaMail");
    Transport.send(message);
    }

    Probably forgot to set the class path so it can find the javax.mail package. If it works when you compile, then make sure you got the same classpath when you run it. Then there should be no problem.

  • JavaMail, ESMTP, problem with this server response: "+  stunnel"

    I need to send message through a STMP server I don't know much about. The server works fine, when using port 25. But I need to send mail through port 465. I've looked around the web, I've searched the forums, but found no solution.
    I've identified, that the server uses some kind of strange "secure" connection. I was told, that is uses SSL, but when I use SMTPSSLTransport, it says the "Unrecognized SSL, plaintext connection?". So I am using the common Transport. This is my code:
                props.put("mail.transport.protocol","smtps");
                props.put("mail.smtp.host", smtpHost);
                props.put("mail.smtp.port", 465);           
                props.put("mail.smtps.starttls.enable","true");
                props.put("mail.smtps.ssl", "true");
                props.put("mail.smtps.socketFactory.port", 465);
                props.put("mail.smtps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                Session session = Session.getDefaultInstance(props);
                session.setDebug(true);
                Transport transport = session.getTransport();
    ...I am getting this output:
    DEBUG: setDebug: JavaMail version 1.4.1
    DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
    DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
    DEBUG SMTP: useEhlo true, useAuth false
    DEBUG SMTP: trying to connect to host "host name of the server", port 465, isSSL false
    220 "host name of the server" ESMTP Sendmail 8.13.1/8.13.1; Fri, 15 Feb 2008 18:10:49 +0100
    + stunnelDEBUG SMTP: connected to host "host name of the server", port: 465
    EHLO "my hostname"
    DEBUG SMTP: bad server response:  + stunnel
    HELO "my hostname"
    250-"my hostname"
    WelcomeDEBUG SMTP: use8bit false
    MAIL FROM:<[email protected]>
    250 STARTTLS
    220 Go ahead
    RCPT TO:<[email protected]>
    DEBUG SMTP: got response code 220, with response: 220 Go ahead
    RSET
    DEBUG SMTP: exception reading response: java.net.SocketException: Connection reset
    javax.mail.MessagingException: Exception reading response;
      nested exception is:
            java.net.SocketException: Connection resetI have no idea, what a stunnel is, but it is causing the problem, I think.
    Does anybody have any ideas what can be wrong? Or does anyone know how to check the server setting? Or what properties can I try to set? (I've tried all possible options of the properties I am already setting in the code).

    You're getting newline (LF without the CR)? If so,
    it's possible that Thunderbird isn't seeing that as
    an end of line and so considers the "+stunnel" to
    be part of the greeting line.
    Either way, there's something messed up in the
    server configuration and you really need to report
    that to the server administrator.
    Also, port 465 is supposed to be an SSL port,
    starting in SSL mode, not starting in plain text
    mode as you're seeing. Again, this is evidence
    that the server is set up incorrectly.
    JavaMail will support STARTTLS just fine, and it
    won't care what port you're using, but that bogus
    "+stunnel" line is a protocol violation that's
    confusing it. Possibly Thunderbird is taking the
    approach of "throw away garbage until I see
    something I recognize", but JavaMail isn't working
    that way.
    If this was a server on the public internet that
    lots of people might encounter, I might be inclined
    to add a workaround to JavaMail. But since this is
    a private server that's clearly configured incorrectly
    and is clearly violating the protocol, I think the best
    thing to do is to get the server fixed.

  • Sun's JavaMail package not working

    I'm trying to implement interface to SendMail java package. On 8.1.7 database.
    I'm following instructions on
    http://www.akadia.com/services/java_mail_plsql.html
    to the dot.
    I got everything loaded and installed without errors.
    But when I'm trying to test package, i'm not getting any errors and I'm not getting message either. Email just dissapears somewhere...
    declare
    errorstatus number;
    errormessage varchar2(2000);
    BEGIN
    ErrorStatus := SendMailJPkg.SendMail(
    SMTPServerName => 'qube.odl.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( '/usr/apps11/email/new_odl_logo.gif','/usr/apps11/email/odl_logo_small.gif' )
    pl(errorstatus);
    pl(errormessage);
    END;
    Is there any setup step for java or something else I'm missing?
    Thanks

    Vladimir,
    No offence, but in the article you refer to, they did say that they only tested against an Oracle 9i database (and not an Oracle 8i database). I also didn't see anything in the article that says that the procedure they describe should work in Oracle 8i as well.
    Apart from that, and excuse me if it is an obvious question, but can you send eMail from the machine where Oracle is running? For example, if the machine is a UNIX machine, can you use the "mail" (or "mailx") command to send eMail.
    I recall working on a UNIX system that demonstrated the behaviour you are describing. When I tried to send eMail to an account that was outside of the UNIX box, I would get no error messages, but the eMail simply seemed to disappear. Perhaps you are experiencing the same problem?
    [Unfortunately, I never resolved this issue, so even if it is your problem, I'm afraid I can't help you resolve it, anyway. Sorry :-( ]
    Good Luck,
    Avi.

  • Javamail deadlock : Please help

    Please help me.
    I have searched everywhere in this forum but I got no answer to my problem so I have decided to make a new post.
    I have been getting this error for a 8days now. I am trying to send an email using Javamail API but Transport.send() and(or) Transport.sendMessage() leads to a deadlock. This is a web application. when the client submits a feedback we would like to send him an email confirmation. But then that page keep running forever. I have tried all but nothing works for me. The weird is that when I turn off tomcat the message is delivered.
    Here is the code
    public class MailUtil
    public static void sendMail(String to, String from,
    String subject, String body, boolean bodyIsHTML)
    throws MessagingException
    // 1 - get a mail session
    //Properties props = new Properties();
    Properties props = System.getProperties();
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.host", smtpserver)
    props.put("mail.smtp.port", 2525);
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.connectiontimeout","20000");
    props.put("mail.smtp.timeout","40000");
    props.put("mail.smtp.quitwait", "false");
    // create some properties and get the default Session
    Session session = Session.getInstance(props, new Authenticator() {
    public PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(authemail, authpassword);
    session.setDebug(true);
    // 2 - create a message
    Message message = new MimeMessage(session);
    java.util.Date today=new java.util.Date();
    message.setSentDate(today);
    message.setSubject(subject);
    if (bodyIsHTML)
    message.setContent(body, "text/html");
    else
    message.setText(body);
    // 3 - address the message
    message.setFrom(new InternetAddress(from));
    message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
    // 4 - send the message
    Transport.send(message);
    this how I called it: MailUtil.sendMail(to, from, subject, body, isBodyHTML);
    props.put("mail.smtp.connectiontimeout","20000");
    props.put("mail.smtp.timeout","40000");
    props.put("mail.smtp.quitwait", "false");
    was just to see if the problem will be solved but no way
    Please help me

    I think that you've posted this to the wrong forum. I suggest you try the JavaMail forum: http://forum.java.sun.com/forum.jsp?forum=43

  • Sendmail using sendmail of Linux

    could someone help me with the problem:
    I need to send mails using sendmail of linux(I cannot user JavaMail API) using Java.
    Thanks in advance.
    Suman

    Hi, I can't find anything about sending email using java classes on the referd www. adress. Is it possible that you post some code about using /usr/sbin/sendmail on the server? Tnx

  • How to mail the html file using javamail????

    hi
    i have captured the output of a jsp page in a html file....
    now i wish to send it in the mail ( *** not as an attachment)
    ie
    i wish the output of the jsp ie the html file to be displayed in
    the message box (ie text area) ..... and then when recieved by the
    receipient it shoud be displayed in the message area....
    is there any way to do this ........

    well as said by my fellow poster googling could have given you quick results.
    Anyways,if you are unable to do so checkout the below code snippet.
    SendMail.java:
    ===========
    import java.io.File;
    import java.io.FileReader;
    import java.io.BufferedReader;
    import java.util.Properties;
    import javax.mail.Session;
    import javax.mail.Message;
    import javax.mail.Transport;
    import javax.mail.internet.InternetAddress;  
    import javax.mail.internet.MimeMessage;
    import javax.activation.*;
    * @Author RaHuL
    * uses SMTP to send Email.
    public class SendMail {
        /** Method used to read contents of html/text/XML file */
        public String readFile(String fileName){
           StringBuffer sb = new StringBuffer();
           BufferedReader input = null;
           try{
               input = new BufferedReader(new FileReader(fileName));
               String str = null;
               while ((str = input.readLine()) != null){    
                      sb.append(line);
           }catch(Exception exp){
               exp.printStackTrace();
           }finally{
                  try {
                        if (input!= null)  
                          input.close(); 
                   }catch (Exception ex) {
                         ex.printStackTrace();
           return sb.toString();
        /** Send an HTML Email with the specific subject to specfic toAddress based on specified fromAddress & Smtp Hostname
          * and returns true on success.
        public boolean sendMail(String toAddress,String fromAddress,String hostName,String subject,String htmlMessage,String contentType) {
           boolean flag = false;    
            try {
                 String to = toAddress;
                 String from = fromAddress;     
                 String host = hostName;
                 // Setting Mail properties
                 Properties props = new Properties();
                 props.put("mail.smtp.host",host);
                 props.put("mail.debug","true");
                 // Getting a New Instance Generated by the API
                 Session session = Session.getInstance(props);
                   NOTE: a Mail Session could be configured and could be got from the Container via JNDI
                         which could be a better practise.
                // Instantiate a message
                Message msg = new MimeMessage(session);
                //Set message attributes
                msg.setFrom(new InternetAddress(from));
                InternetAddress[] address = {new InternetAddress(to)};
                msg.setRecipients(Message.RecipientType.TO, address);
                // Setting Subject Type
                msg.setSubject(subject);
                msg.setSentDate(new Date());
                // Setting Content Type
                msg.setContent(contentType);
                // Set message content
                msg.setText(htmlMessage);
                //Send the message
                Transport.send(msg);
                flag = true;
            }catch (Exception mex) {
             // Prints all nested (chained) exceptions as well
                mex.printStackTrace();
         return flag;
        public static void main(String args[]){
            SendMail sm = new SendMail();
            String htmlMessage = sm.readFile("myHtmlFile.html");
            boolean flag = sm.sendMail("[email protected]","[email protected]","your.smtp.server","EMail SubJect",htmlMessage,"text/html");
            if(flag)
              System.out.println("MAIL SENT SUCCEFULLY");
             else
              System.out.println("MAIL SENDING FAILURE");                          
    }NOTE:
    =====
    Make sure you inculde javamail & java activation libraries.
    Hope that might help :)
    REGARDS,
    RaHuL

Maybe you are looking for

  • 8.6 to 9.2.1 to 10.2

    I am trying to update an old machine I have for my daughter. It is a G4-PCI with 120 Gb drive, and 256 RAM. It hasn't run well for a long time, so I decided rather than use it for a paper weight, I would give it an overhaul and make it a usable machi

  • I set up ITunes etc. but keep getting the same error message: itunes cant connect ....error

    I'm getting very annoyed. Last night I bought an Ipod Touch for my son's birthday today. Tried to set it up last night...no go. I figured I was just tired and thought to try again this morning. I hooked the Touch up to my PC (running WIn7 Ultimate),

  • How can I get numbers purchased for my ipad onto my mac air?

    I have numbers on my iphone and ipad. I just purchased a new mac air and I want to use the app on it without paying for it again. How do I do this?

  • Table Data Alignment issue in DW CS4

    Hi, I'm creating a web site in DW CS4. I'm trying to align my table that I created for my contact form. I got it like I want it except for one slight issue: my submit button is not aligning with the rest of the form elements. I'm not sure how to add

  • Quicktime file downloaded before uploaded-- viewable?

    If a video QuickTime file is downloaded before it is fully uploaded is it viewable in any way by the downloader? Summary: A sender began uploading a 700 meg motion video QuickTime movie file to an ftp site. The QuickTime definitely had motion prior t