Sending email using SMTP and Java

Hi guys
I am using the following code to send an email:
private void sendEmail(String mDate, String time) {       
        Date date = new Date();
        DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL, Locale.ENGLISH);
        // Open port to server
        try {
          smtpSocket = new Socket(SMTP_SERVER, SMTP_PORT);
          os = new DataOutputStream(smtpSocket.getOutputStream());
          is = new DataInputStream(smtpSocket.getInputStream());
          // Connection was made.  Socket is ready for use.
          if(smtpSocket != null && os != null && is != null) {
            try {
                // email header
                os.writeBytes("HELO\r\n");
                // set the reply email address
                os.writeBytes("MAIL From: <[email protected]>\r\n");
                // give the address of the people that we want the email sent to
                for(int i=0; i<RECIPIENTS.length; i++) {
                    os.writeBytes("RCPT To: <" + RECIPIENTS[i] + ">\r\n");
                    System.out.println(RECIPIENTS);
// data header
os.writeBytes("DATA\r\n");
os.writeBytes("X-Mailer: Via Java\r\n");
os.writeBytes("DATE: " + dateFormat.format(date) + "\r\n");
os.writeBytes("From: Characterisation System Update\r\n");
os.writeBytes("Mime-Version: 1.0\r\n");
os.writeBytes("Content-Type: text/html; charset=\"ISO-8859-1\"\r\n");
//os.writeBytes("Content-Transfer-Encoding: 7bit;\r\n");
for(int i=0; i<RECIPIENTS.length; i++) {
os.writeBytes("To: <" + RECIPIENTS[i] + ">\r\n");
// get the details of the test and enter them into the message body
String message = "<HTML><BODY>" +
"\r\nThe following System has not received a data packet for at leat 1 hour:" +
"\r\n<BR/><BR/><B>System:</B> " + rackName +
"\r\n<BR/><B>Time Last Pkt. Received:</B> " + time +
"\r\n<BR/><B>Date Last Pkt. Received:</B> " + mDate +
"\r\n<BR/><B>Job Number:</B> " + jobNoDispLabel.getText() +
"\r\n<BR/><B>Device:</B> " + deviceDispLabel.getText() +
"\r\n<BR/><B>Run Number:</B> " + runNoDispLabel.getText() +
"\r\n<BR/><B>Current Temperature:</B> " + tempDispLabel.getText() +
"\r\n<BR/><B>Current Module:</B> " + moduleDispLabel.getText() +
"\r\n<BR/><B>Current Test:</B> " + testingDispLabel.getText() +
"\r\n<BR/><BR/>This does not gurantee that the system has crashed!" +
"\r\n</BODY></HTML>";
os.writeBytes("Subject: " + rackName + " Packet Warning\r\n");
os.writeBytes(message + "\r\n");
os.writeBytes("\r\n.\r\n");
os.writeBytes("QUIT\r\n");
// Now send the email off and check the server reply.
// Was an OK is reached you are complete.
String responseline;
//DataInputStream d = new DataInputStream(is);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
while((responseline = reader.readLine())!= null) { 
if(responseline.indexOf("Ok") != -1) {
break;
} catch(Exception e) {
System.out.println("Cannot send email as an error occurred.");
e.printStackTrace();
catch(Exception e) {
System.out.println("Host " + SMTP_SERVER + "unknown");
e.printStackTrace();
} finally {
// close all of the data streams
try {
if(!smtpSocket.isClosed()) {
smtpSocket.close();
smtpSocket = null;
} catch(Exception e) {
e.printStackTrace();
try {
if(os != null) {
os.close();
os = null;
} catch(Exception e) {
e.printStackTrace();
try {
if(is != null) {
is.close();
is = null;
} catch(Exception e) {
e.printStackTrace();
i have used an example on the web to help me do this, so it may look familiar!!
It works fine when i run the program in debug mode but doesn't work when i run the jar file, i was wondering if anyone could help me understand why? or give me a clue as to where to look as i have had the strange realisation that i rarely compile my code up to be used by other people!!
sad but true! Also apologies if i haven't posted adequate information, this is the first time i have posted on the forum asking for help!
Anyway help would be most appreciated and thanks in advance

Sorry, by debug mode i mean running it using netbeans 5.5 and clicking on the "run main project" icon.
Once i have cleaned and built the main project all of the files are put into the jar file. Once i have done that i double click on the jar icon
is that ok? there doesn't seem to be any errors

Similar Messages

  • How to remove error 59 which occurred while using Send Email Using Smtp Client .VI in Labview 2013.

    Hi,I am trying to run Send Email Using Smtp Client .VI in Labview 2013 examples ,but it gives error 59.Please can anyone suggest how to remove the error.The printscreen is attached below.
    Solved!
    Go to Solution.
    Attachments:
    error.docx ‏310 KB

    Thanks for the help,but i have set the parameters right but still it does not work for me.Please suggest me reasons and how to correct them.
    Attachments:
    error.docx ‏270 KB

  • Sending email using URL and URLConnection

    I have been having trouble trying to send an email using URL.
    I have specified the mail host using: mailHost = Options.getProperty("mailHost", "mail.myisp.com");
    and tried to send the email using this:
    try
    try
    URL u = new URL("mailto:"+recipient);
    URLConnection c = u.openConnection();
    c.setDoInput(true);
    c.setDoOutput(true);
    c.connect();
    PrintWriter out = new PrintWriter(new OutputStreamWriter(c.getOutputStream()));
    out.print("From:\"ME\" \n");
    out.print("Subject: Stuff \n");
    out.print("blah blah blah");
    out.close();
    catch etc. . .
    I recieve the email with the subject line there, but the actual body of the email is empty. Anyone know what I have done wrong? This is part of a standalone application that was turned into an .exe with jbuilder9.

    That worked, thanks!
    Out of curious, why the surprise that it worked?
    Its not that bad is it?Yeah, I didn't know that mailto: support was there either, is all. The blank line thing is just common in HTTP and sendmail so, I figured that would be the solution.
    I don't know that it's bad... if it works. Generally, the JavaMail APIs are a more robust way of sending mail, but if mailto: URLs work, and it's simple mail, then I see no reason not to use it.

  • Unable to send emails using SMTP Plug In

    Hi all.
    I am trying to configure SAPConnect so that I can send emails from SAP to
    external domains. I have done all settings in SCOT. But our Outgoing SMTP Server needs authentication. So in my JOB TRACE I am getting error '530 Authentication Required'.
    In transaction RZ10 where I have maintained Instance Profile IDS_DVEBMGS00_IDES-SERVER
    I have set Parameter: icm/server_port_0 with value PROT=SMTP, PORT=25. Is there any way I can pass "Authentication Required" as a value here or in transaction SCOT.
    Anyone who has a solution plz help me.
    Thanks and regards.
    Vipin Varghese.

    Thanks all for the help.
    The server that I am supposed to configure that is the email server that you are talking about right?
    I m fairly new into WF and these Basis steps are new for me.
    There are 4 profiles created in RZ10 - 2 start profiles and 2 instance profiles.
    I am making changes in an instance profile. But after the changes when I try to activate, its showing some warnings and errors. But somehow it gets activated and an instance profile with version 2 is actively saved.
    Also when I open MS OUTLOOK and go to the account settings, for Outgoing server ( SMTP ) , Authentication Required checkbox has been marked.
    Now is any one of these the problem?
    Regards.
    Vipin Varghese.

  • Cannot send email using SMTP

    Hi,
    For the last three days I have been unable to send any email via outlook using the SMTP server (mail.btinternet.com). I get repeated requests to enter my network password, but it is not accepted. The password is correct (I have tried retyping it numerous times) and I can still log into webmail using it. This problem occured on both my computers simutaneously and without any changes being made, so it is not setting related. I have tried creating the account again, but it fails due to this issue. Incoming mail is unaffected.
    Please could someone offer some help? Is there a known issue as I am unable to find anything to suggest there is on the BT service status page?
    Andy

    Hi bernies41802,
    Thanks for posting.
    Sorry for the problems you're having.  Has your email address been migrated to the new BT Mail platform?  You can check here - Check which BT email service you are using
    If it shows on the new BT Mail platform double check your settings are correct here - BT Mail: What are the settings for outgoing and incoming mail servers?
    Post back and let me know how you get on.
    All the best,
    Robbie
    BTCare Community Mod
    If we have asked you to email us with your details, please make sure you are logged in to the forum, otherwise you will not be able to see our ‘Contact Us’ link within our profiles.
    We are sorry that we are unable to deal with service/account queries via the private message(PM) function so please don't PM your account info, we need to deal with this via our email account :-)
    If someone answers your question correctly please let other members know by clicking on ’Mark as Accepted Solution’.

  • Sending Email Using Automator and Mail

    Every year I shave my head for a charity called St. Baldrick's. I raise money and then send pictures to all the people who donate to me shaving my head. I was wondering if there was a way to send a group of people an email with attachments in automator. Not only this but something special. Many email programs will mark something as spam if it is send to more then four people at a time. I would like to have an action or something in automator so that I can specify who to send it to and then have them sent as individual messages. This can be a real pain even if I were to copy and paste stuff. Is there a way to make my life easier so this doesn't take up so much time?

    I ran accross this randomly so sorry if this is irrelevent with timing. It seems however that Text Expander might be what you need. It is a mac program though, not ios.
    http://www.smilesoftware.com/TextExpander/

  • Sending email using IMAP through SMTP Port 587

    Hi,
    I have been sending Mail Merged email to people in organizations that I am active in, using IMAP embedded in StarOffice 5.2 (on Windows 98 Second Edition). This worked fine until a few weeks ago when I received an error message stating that AOL, as part of their anti-spam efforts, was no longer accepting third-party emails on default port 25. All third-party email must now use port 587. I looked in the IMAP dialog and in the Tools -> Options dialog, but did not see any place to change the SMTP port. The AOL error message information page had instructions for changing the port in other applications (Outlook, Eudora, etc.), but not for StarOffice. So, I have some questions:
    1.Is it possible to change the port in StarOffice 5.2?
    2.If not, how does StarOffice 8 send Mail Merged email? Does it use IMAP, and if so, can the port be changed?
    3.Also, I like the integrated configuration in StarOffice 5.2, where database fields can be directly accessed in the Insert -> Fields -> Other dialog. In looking at the Mail Merge section in "SO8_What's New.pdf", it appears that Mail Merge in StarOffice 8 is restricted to predefined fields. Could I still access fields from my existing databases?
    These is a lot of questions, but right now I am blocked from sending Mail Merged emails which is imparing communications with volunteers who are running educational programs. I appreciate any and all help that anyone can provide.

    Please try this out!!!!!!!!!
    You can send emails using Outlook also. You can send email over Microsoft Exchange with this object (or another email server, using IMAP/POP).
    Sub SendMailOutlook(aTo, Subject, TextBody, aFrom)
    'Create an Outlook object
    Dim Outlook 'As New Outlook.Application
    Set Outlook = CreateObject("Outlook.Application")
    'Create e new message
    Dim Message 'As Outlook.MailItem
    Set Message = Outlook.CreateItem(olMailItem)
    With Message
    'You can display the message To debug And see state
    '.Display
    .Subject = Subject
    .Body = TextBody
    'Set destination email address
    .Recipients.Add (aTo)
    'Set sender address If specified.
    Const olOriginator = 0
    If Len(aFrom) > 0 Then .Recipients.Add(aFrom).Type = olOriginator
    'Send the message
    .Send
    End With
    End Sub

  • Since upgrading my computer last week i cannot send emails using talktalk, i can send via ipad and phone so not the server

    Since upgrading my system i have been unable to send emails using talktalk although i can receive them  i have no problem sending them via ipad or phone. can any one help please

    Open Mail -> Preferences -> Accounts.  Select the TalkTalk account and then the 'Account Information' tab. Drop down the 'Outgoing Mail Server (SMTP)' menu and select 'Edit SMTP Server List'.  Ensure that 'Server Name' under 'Account Information' is set to "smtp.talktalk.net".  You may also need to configure settings under the 'Advanced' tab. 
    More info here:
    http://help.talktalk.co.uk/app/answers/detail/a_id/1668/~/what-are-talktalk's-em ail-settings%3F#TalkTalk

  • When I send emails using my iPad, recipients are telling me that I am sending them blank emails.  I've had some of them forward the emails back to me so I can take a look and it seems that my message is actually there but the text is white...

    When I send emails using my iPad, some recipients are telling me that I am sending them blank emails.  I've had some of them forward the emails back to me so I can take a look and it seems that my message is actually there but the text is white.  Interestingly enough, I was a Windows user just a few months ago and I was on the receiving end of this same problem with someone who was sending emails from her iPhone.  I don't believe it is happening every time but if it happens even once it's a problem.  Any idea what's going on? 

    Oddly enough, having reported the problem it appears to have fixed itself. There may be some combination swipe gesture that triggers it is all I can think because I suddenly manged to zoom my display x3 by double tapping three fingers. Took me a while to sort this out but then when I got back home I could suddenly see all my emails again. Bizarre!

  • Problem with Thunderbird email: When I send email using a mailing list, with my email included in the list, the message shows up in my Sent list and others rece

    Problem with Thunderbird email:
    When I send email using a mailing list, with my email included in the list, the message shows up in my Sent list and others receive it but it does not come to my email Inbox. The same problem occurs when I send the email to the mailing list addresses individually. When I send a simple test message to myself, I do receive it in my Inbox. Can you help me??
    Bob Greenman

    Are you using either cc or bcc? Is googlemail involved? Some email providers suppress cc's and bcc's to oneself since you will have a copy in your Sent folder.

  • I am unable to send emails using mail from my btinternet and yahoo accounts similar problem to others with mobile me accounts on lion any suggestions?

    I am unable to send emails using mail from my btinternet and yahoo accounts similar problem to others with mobile me accounts on lion any suggestions?

    Do I need to delete all my email accounts and start again?

  • How to send Email with Cc and Bcc using MailPackage

    Hi ,
    we are using Mail Package to send the Email using Mail Adapter.We have a requirement where we need to send Email with Cc and Bcc using Mail Package .
    Can we send Cc and Bcc using Mail Package ?
    Thanks
    Rajesh .

    HI Rajesh,
    There is a standard structure for Receiver Mail adopter which we can get from SAP market Place but it is not provided with CC if u want to use CC then you have to go with Dynamic Configuration.
    DynamicConfiguration configuration = (DynamicConfiguration) container.getTransformationParameters().getStreamTransformationConstants.DYNAMIC_CONFIGURATION);
    /*any other required fields*/
    DynamicConfigurationKey key = DynamicConfigurationKey.create("http://sap.com/xi/XI/System/Mail", "THeaderCC");
    configuration.put(key, "ccemail @ test.com");
    Regards
    Praveen Reddy
    Edited by: Maareddy Praveen Reddy on Aug 10, 2011 12:17 PM

  • How to send emails using java code

    Hi,
    can any give me some sample code for sending emails using java language

    JavaMail quick start
    jGuru: Fundamentals of the JavaMail API

  • Loss of sending email using WIFI

    As of this morning 8-20-08, after updating to 2.02, I no longer am able to send emails using my own wireless network. Previously this was no problem. Neither Fido or Apple have any idea of what I am talking about. Fido washed their hands as they do not support WIFI. How convenient, they sell the phone and charge for the service but do not support it. Videotron, my ISP, thinks the issue is my wireless router but I can send via gmail so that's out. I resovled the problem by configuring my accounts to use my gmail smtp server as a second option and now the spinning wheel is short lived and messages are sent.
    I'm sorry to say that I had fallen for all the hype about Apple but truth is they are but a Microsoft wannabe.
    Disinchanted

    So here's the wierd thing.
    I was having the same problems. Set up SMTP for Videotron when at home using relais.videotron.ca SMTP with no authenticationon port 25 & all was good in the world. However when I went out, bang. Nothing. Couldn't send a mail for love nor money.
    Thought aboutit & changed settings to use relais.videotron.ca SMTP, but this time using authentication of vltl** / password credentials with no SSL (Videotron doesn't use SSL) and again everything was fine. Of course, when I got home again, bang. Everything fell over & no more mail sending foe me!
    So I figure, when I'm at home I'm on my trusted network at port 25, I don't need authentication and all is good, but when I'm out i'm seen as potential SPAM by port 25 on videotron & get blocked.
    Tried using port 587 instead when for both home & mobile but had no luck either.
    Then a strange thing happened. I'd resolved to having to set up 2 SMTP servers on my iPhone & switching between the two based on where I was. Pain in the a**, but there's always a trade off for early adopter technology So I set up my primary SMTP to use port 25 with no authentication, and a secondary server to use the same relais.videotron.ca outgoing server, but this time WITH authentication using vltl** \ password credentials.
    After a walk to the shop when I'd been on my secondary SMTP server (successfully sending & recieving) I came home & inadvertantly forgot to swith back to my primary SMTP. Recieved a mail & then responded with no problem!
    Net result, I now have a permanently switced off primary server & a permanently switched on secondary server which uses relais.videotron.ca details with vltl** \ password authentication credentials active (like I did on my old silver iPhone) & all is good in the world, both at home & out mobile, both for sending & recieving!
    Will field test some more tomorrow but it may be a 2.0.2 bug where ther primary server details fcuk up whereas the secondary server details are stable.
    So long as it works, who cares!
    Jof

  • IPhone cannot send email using Yahoo account. iPhone no envia correo Yahoo.

    Hi Everyone,
    I just got my iPhone from Movistar Venezuela and I've found I'm unable to send email using my Yahoo account. However, I can receive Yahoo email just fine (paid $20 for Mail Plus subscription), my GMail account can send and receive perfectly, and I can go surfin' Safari with no problems too.
    The error message I get is "Cannot send mail: an error occurred while delivering this message". I called Movistar Customer Support and they said everything was fine on their end...
    In typical Apple fashion, the error message is so simple I have no idea where the problem is. Does anyone know how can I get more information and how to solve this annoying problem? My Yahoo account is actually my primary account...
    Thanks in advance!
    Saludos a todos,
    Acabo de comprarme un iPhone de Movistar en Venezuela y me encuentro sin poder enviar emails con mi cuenta Yahoo. Sin embargo, si puedo recibir correo Yahoo bien (pague $20 por mi suscripcion a Mail Plus), mi cuenta de GMail si puede enviar y recibir email sin problema y puedo navergar con Safari sin ningun problema.
    El mensaje de error que recibo es el siguiente": "No se puede enviar correo: se ha producido un error al enviar el mensaje". Llame a Atencion al Cliente de Movistar y me dijeron que no habia ningun problema con mi linea o con su servicio de datos...
    Como tipica cosa Apple, el mensaje de error es tan simple que no tengo NI IDEA de cual es el problema. Alguien mas ha sufrido este problema? Sabe alguien como puedo obtener mas informacion de este error y como solucionarlo? Lamentablemente, mi cuenta Yahoo es mi correo principal...
    Gracias de antemano!

    Creo que resolvi el problema, temporalmente.
    1) Borra tu cuenta
    2) Vuelvela a crear
    3) Ve a Ajustes
    4) Ve a Mail Contactos Calendarios
    5) Ve a la cuenta problematica
    6) Ve a SMTP
    7) Anadir nuevo
    8)
    Nombre servidor: smtp.mail.yahoo.com
    Nombre de usuario: no dejar vacio
    Contrasena: no dejar vacio
    Usar SSL: si
    Autenticacion: Contrasena
    Puerto del Servidor: 25
    Lo consegui de aqui: http://www.emailaddressmanager.com/tips/mail-settings.html
    Dime que tal te funciona.
    I think I solved the issue, temporarily at least
    1) Delete account
    2) Create again
    3) Go to settings
    4) Go to Mail, Contacts, Calendars
    5) Open problematic account
    6) Go to SMTP
    7) Add a new server
    8)
    Name: smtp.mail.yahoo.com
    User name: do not leave blank
    Password: do not leave blank
    SSL: Yes
    Autentication: Password
    Port: 25
    I got this info from: http://www.emailaddressmanager.com/tips/mail-settings.html
    Let me know how this works

Maybe you are looking for