Java mail - unknown host
hi
I am quite new to java.. I have written some code that requests user input to create a mail then should be sent.
I am using my companies smtp address to send it through but i keep getting the exception unknown host, however when a colleague tries to run my code on there pc on the same network it works correctly. Really impressed my code works but i want to play with it and add things to it and cannot!
Is there any settings or rights i should have on my pc to enable me to get this code to work. Also does anyone know of any external smtp hosts i can send mails from.
I can ping the smtp from dos and that works but will not recognise in code
thanks
A
import javax.mail.Address;
import javax.mail.Session;
import javax.mail.Authenticator;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.AddressException;
import javax.mail.internet.MimeMessage;
import java.io.*;
import java.util.Properties;
* Created by IntelliJ IDEA.
* User: ai011767
* Date: Apr 8, 2003
* Time: 3:24:57 PM
* To change this template use Options | File Templates.
public class JavaMail {
Address recipientEmail;
String ccAddress;
Address senderAddress;
String subject;
String message;
Properties p;
String host;
//*Address replyTo;
public JavaMail(String propertiesPath) {
try {
FileInputStream fis = new FileInputStream(propertiesPath);
p = new Properties();
p.load(fis);
host = p.getProperty("host");
System.err.println(host);
catch (Exception e) {
System.out.println("file not found");
public void mail(Address recipientAddress, Address senderAddress, Address reply[], String subject, String message) {
p.put("mail.smtp.host", host);
try {
Session s = Session.getInstance(p, null);
MimeMessage mess = new MimeMessage(s);
mess.setText(message);
mess.setSubject(subject);
Address a = new InternetAddress();
mess.addRecipient(MimeMessage.RecipientType.TO,recipientAddress);
mess.setFrom(senderAddress);
mess.setReplyTo(reply);
Transport.send(mess);
catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use Options | File Templates.
public void doWork() {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.println("Type in recipents e-mail Address");
String strRecipientEmail = in.readLine();
Address recipientAddress = new InternetAddress(strRecipientEmail);
System.out.println("Type in reply address");
String strreplyTo =in.readLine();
Address replyTo = new InternetAddress(strreplyTo);
Address[] reply = new Address[1];
reply[0] = replyTo;
System.out.println("Type in Senders E-mail Address");
String strSenderAddress = in.readLine();
Address senderAddress = new InternetAddress(strSenderAddress);
System.out.println("Type in Subject");
subject = in.readLine();
System.out.println("Type in Message");
message = in.readLine();
this.mail(recipientAddress, senderAddress, reply, subject, message);
catch (Exception e) {
System.out.println("No Line to read");
public static void main(String args[]) {
JavaMail jm = new JavaMail(args[0]);
jm.doWork();
Similar Messages
-
HI,
When i run my application i got the below erros.. what could be the problem
Unknown host D:\<dir_name>
Context : External procedure experienced a network error communicating with mail server. Retrying.
and also i have valid directory with write permission...
Thanks in advance
-GGYahoo and Gmail support should be able to help you.
Not related to Firefox support, web mail doesn't use POP or SMTP protocols which is what email clients such as Thunderbird use for communicating with email servers. -
Unknown Host : mail.sap.corp
Hi expert,
This is my first time configure the smtp server in CE 7.1 SP3. I have read the following threads:
Re: Guided Procedures - set mail smtp host Re: Mail settings for Guided Procedures
And I have tried this:
1. Go to Guided procedure ->
Administration-> Administer BMF->Clients
->select iForms Processor -> press Settings button
-> Mail Sending tab.
2. Set your smtp server in SMTP Server field.
3. Press Save button.
You can test mail sending by pressing Test button
but first you should
configure the mail of the administrator of BMF and
the mail of the administrator of the client
(iForms Processor). Please follow instruction below
BMF Administrator's mail:
1.Go to Guided procedure ->
Administration-> Administer BMF->Settings.
2.Input the mail in Administrator Mail files.
3.Press Save button.
iForms client Administrator's mail:
1. Go to Guided procedure ->
Administration-> Administer BMF->Clients
->select iForms Processor
2. Press Edit button.
3. Input the mail in Administrator Mail files.
4. Press Save button.
and
Set the SMTP settings (smtp.sever property) in Configtool under cafeugp~model
However, the later method do not allow me to modify the configuration. And both method failed and I still received the following exception:
Unknown SMTP host: mail.sap.corp
javax.mail.MesssagingException: Unknown SMTP host: mail.sap.corp
can help?
thank youHi,
maybe you should try this:
1. Under Guided Procedures, choose Administration u2192 Administer BMF.
2. Choose Clients, then under BMF Clients choose Settings, and then choose Mail Sending.
3. Enter the data for SMTP Server and Mail Transport Protocol. For example:
SMTP Server: mail.sap.corp
Mail Transport Protocol: smtp
4. Save
or try the config tool as explained on the following sap help page:
http://help.sap.com/saphelp_nwce10/helpdata/en/e0/e3934249c30c31e10000000a1550b0/frameset.htm
smtp.server
smtp.service_user_mail
properties.
It may be useful to restart the server after changing this.
best regards,
v s -
Unknown exception triggered by my Java Mail call
I don't know if there is a Java Mail specific forum or not, so I put this here.
I'm getting an IOException when I attempt to send my message. Below is the full text I see. If you understand what I'm doing wrong, please let me know. The code it attempting to send a multipart MIME message. It has a body which is "See attached file(s).\n.". I also attached a small text file. Finally, since this was just going to be a test e-mail, I added myself as a recipient.
DATA
354 Enter mail, end with "." on a line by itself
java.io.IOException: No content
at javax.mail.internet.MimePartDataSource.getInputStream(MimePartDataSource.java:106)
at javax.activation.DataHandler.writeTo(DataHandler.java:304)
at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1350)
at javax.mail.internet.MimeMessage.writeTo(MimeMessage.java:1683)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:585)
at javax.mail.Transport.send0(Transport.java:169)
at javax.mail.Transport.send(Transport.java:98)
at m3.main(m3.java:518)
Exception of type class javax.mail.MessagingException
javax.mail.MessagingException: IOException while sending message;
nested exception is:
java.io.IOException: No content
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:625)
at javax.mail.Transport.send0(Transport.java:169)
at javax.mail.Transport.send(Transport.java:98)
at m3.main(m3.java:518)
Caused by: java.io.IOException: No content
at javax.mail.internet.MimePartDataSource.getInputStream(MimePartDataSource.java:106)
at javax.activation.DataHandler.writeTo(DataHandler.java:304)
at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1350)
at javax.mail.internet.MimeMessage.writeTo(MimeMessage.java:1683)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:585)
... 3 moreIf that is the case, I'm setting the body wrong. The existing code is too complex for easy posting here. However, in a few hours, I should be able to create a simplified version.
-
Problem in sending mail using java mail api
This is the pogram I am using as of now to send a mail to yahoo id.
import javax.mail.*;
import javax.mail.internet.*;
public class SendingMail2
public SendingMail2()
try
String from = "ravikiran_sunrays";
String to = "[email protected]";
String subject = "the subject u wanna send ";
String cc="[email protected]";
String bcc="[email protected]";
String text="the matter that u wanna send ";
java.util.Properties prop = System.getProperties();
prop.put("mail.smtp.host","mail.yahoo.com");
//prop.put("http.proxyHost",System.getProperty("http.proxyHost"));
//prop.put("http.proxyPort","8080");
//prop.put("http.proxyPort",System.getProperty("http.proxyPort"));
//prop.put("http.proxyHost","172.19.48.201");
//System.getProperties().setProperty("http.proxyPort","8080");
//System.getProperties().setProperty("http.proxyHost","172.19.48.201");
Session ses = Session.getInstance(prop,null);
MimeMessage message = new MimeMessage(ses);
try
Address fromAddress = new InternetAddress(from);
message.setFrom(fromAddress);
message.setSubject(subject);
Address[] toAddress = InternetAddress.parse(to);
Address[] cc_address=InternetAddress.parse(cc);
Address[] bcc_address=InternetAddress.parse(bcc);
message.setRecipients(Message.RecipientType.TO,toAddress);
message.setRecipients(Message.RecipientType.CC,cc_address);
message.setRecipients(Message.RecipientType.BCC,bcc_address);
message.setSentDate(new java.util.Date());
message.setText(text);
Transport.send(message);
System.out.println("Mail Successfully Sent");
catch(Exception e)
System.out.println("Problem " + e);
catch(Exception e)
System.out.println("Problem " + e);
public static void main(String[] args)
SendingMail2 sendingMail2 = new SendingMail2();
This is the exception I am getting when I try 2 execute that program.
avax.mail.SendFailedException: Sending failed;
nested exception is:
javax.mail.MessagingException: Unknown SMTP host: mail.yahoo.com;
nested exception is:
java.net.UnknownHostException: mail.yahoo.comlisten buddy
this is a class i made it is easy to understand it sends mails and check inbox just adduser from telnet with remote manager in james create the three accounts i am using and then use this class and its methods
also the next class that contains the mails test my class and what i am saying
import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class MailClient
extends Authenticator
public static final int SHOW_MESSAGES = 1;
public static final int CLEAR_MESSAGES = 2;
public static final int SHOW_AND_CLEAR =
SHOW_MESSAGES + CLEAR_MESSAGES;
protected String from;
protected Session session;
protected PasswordAuthentication authentication;
public MailClient(String user, String host)
this(user, host, false);
public MailClient(String user, String host, boolean debug)
from = user + '@' + host;
authentication = new PasswordAuthentication(user, user);
Properties props = new Properties();
props.put("mail.user", user);
props.put("mail.host", host);
props.put("mail.debug", debug ? "true" : "false");
props.put("mail.store.protocol", "pop3");
props.put("mail.transport.protocol", "smtp");
session = Session.getInstance(props, this);
public PasswordAuthentication getPasswordAuthentication()
return authentication;
public void sendMessage(
String to, String subject, String content)
throws MessagingException
System.out.println("SENDING message from " + from + " to " + to);
System.out.println();
MimeMessage msg = new MimeMessage(session);
msg.addRecipients(Message.RecipientType.TO, to);
msg.setSubject(subject);
msg.setText(content);
Transport.send(msg);
public void checkInbox(int mode)
throws MessagingException, IOException
if (mode == 0) return;
boolean show = (mode & SHOW_MESSAGES) > 0;
boolean clear = (mode & CLEAR_MESSAGES) > 0;
String action =
(show ? "Show" : "") +
(show && clear ? " and " : "") +
(clear ? "Clear" : "");
System.out.println(action + " INBOX for " + from);
Store store = session.getStore();
store.connect();
Folder root = store.getDefaultFolder();
Folder inbox = root.getFolder("inbox");
inbox.open(Folder.READ_WRITE);
Message[] msgs = inbox.getMessages();
if (msgs.length == 0 && show)
System.out.println("No messages in inbox");
for (int i = 0; i < msgs.length; i++)
MimeMessage msg = (MimeMessage)msgs;
if (show)
System.out.println(" From: " + msg.getFrom()[0]);
System.out.println(" Subject: " + msg.getSubject());
System.out.println(" Content: " + msg.getContent());
if (clear)
msg.setFlag(Flags.Flag.DELETED, true);
inbox.close(true);
store.close();
System.out.println();
====================================
testing this class
=======================================
public class JamesConfigTest
public static void main(String[] args)
throws Exception
// CREATE CLIENT INSTANCES
MailClient redClient = new MailClient("red", "localhost");
MailClient greenClient = new MailClient("green", "localhost");
MailClient blueClient = new MailClient("blue", "localhost");
// CLEAR EVERYBODY'S INBOX
redClient.checkInbox(MailClient.CLEAR_MESSAGES);
greenClient.checkInbox(MailClient.CLEAR_MESSAGES);
blueClient.checkInbox(MailClient.CLEAR_MESSAGES);
Thread.sleep(500); // Let the server catch up
// SEND A COUPLE OF MESSAGES TO BLUE (FROM RED AND GREEN)
redClient.sendMessage(
"blue@localhost",
"Testing blue from red",
"This is a test message");
greenClient.sendMessage(
"blue@localhost",
"Testing blue from green",
"This is a test message");
Thread.sleep(500); // Let the server catch up
// LIST MESSAGES FOR BLUE (EXPECT MESSAGES FROM RED AND GREEN)
blueClient.checkInbox(MailClient.SHOW_AND_CLEAR);
=======================================================
it suppose to print this
Clear INBOX for red@localhost
Clear INBOX for green@localhost
Clear INBOX for blue@localhost
SENDING message from red@localhost to blue@localhost
SENDING message from green@localhost to blue@localhost
Show and Clear INBOX for blue@localhost
From: green@localhost
Subject: Testing blue from green
Content: This is a test message
From: red@localhost
Subject: Testing blue from red
Content: This is a test message
thanks a lot
but i need ur help plzzzzzzzzzzzz
i can create account from telnet
but how i can create a new account from java .. a jsp page that i made to create a new account on the server
plzzzzzzzz help me
bye -
Hi, i have written a simple code to send mail thru java... but it doesnt work... control never comes back after stepping in to the send function.. no exceptions.. no mails sent.. nothin.. cud someone hel me out??
sometimes i get this exception after a long time:
javax.mail.MessagingException: Exception reading response;
nested exception is:
java.net.SocketException: Connection reset
at com.sun.mail.smtp.SMTPTransport.readServerResponse(Unknown Source)
at com.sun.mail.smtp.SMTPTransport.openServer(Unknown Source)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(Unknown Source)
at javax.mail.Service.connect(Unknown Source)
here is the code snippet:
public void mySend() throws Throwable
Properties p = System.getProperties();
p.put("mail.transport.protocol", "smtp");
p.put("mail.smtp.host", "smtp.gmail.com");
p.put("mail.smtp.port", "465");
p.put("mail.smtp.starttls.enable", "true");
p.put("mail.smtp.auth", "true");
Authenticator authenticator = new Authenticator()
protected PasswordAuthentication getPasswordAuthentication()
return new PasswordAuthentication("vicky.bhandari", "password");
Session session = Session.getInstance(p, authenticator);
SMTPMessage message = new SMTPMessage(session);
InternetAddress fromAddress = new InternetAddress("[email protected]");
InternetAddress toAddress = new InternetAddress("[email protected]");
message.setSubject("Test");
message.addRecipient(Message.RecipientType.TO, toAddress);
message.setFrom(fromAddress);
SMTPTransport.send(message);
Could someone please help me out??Hey,
Im currently having problems with the code below:
public class SendMail {
private static final String SMTP_HOST_NAME = "smtp.gmail.com";
private static final String SMTP_AUTH_USER = "[email protected]";
private static final String SMTP_AUTH_PWD = "**************";
public void sendMail(String recipients[ ], String subject, String message , String from) throws MessagingException{
boolean debug = false;
Properties props = System.getProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.port", "465");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getDefaultInstance(props, auth);
session.setDebug(debug);
Message msg = new MimeMessage(session);
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++)
addressTo[i] = new InternetAddress(recipients);
msg.setRecipients(Message.RecipientType.TO, addressTo);
msg.setSubject(subject);
msg.setContent(message, "text/plain");
Transport tr = session.getTransport("smtp");
tr.connect(SMTP_HOST_NAME, SMTP_AUTH_USER, SMTP_AUTH_PWD);
msg.saveChanges(); // don't forget this
//tr.sendMessage(msg, msg.getAllRecipients());
tr.close();
tr.send(msg);
public class SMTPAuthenticator extends Authenticator
public PasswordAuthentication getPasswordAuthentication()
String username = SMTP_AUTH_USER;
String password = SMTP_AUTH_PWD;
return new PasswordAuthentication(username, password);
the error i am receiving is:
java.lang.NoClassDefFoundError: javax/mail/Authenticator
java.lang.Class.getDeclaredConstructors0(Native Method)
java.lang.Class.privateGetDeclaredConstructors(Unknown Source)
java.lang.Class.getConstructor0(Unknown Source)
java.lang.Class.newInstance0(Unknown Source)
java.lang.Class.newInstance(Unknown Source)
org.apache.struts.util.RequestUtils.applicationInstance(RequestUtils.java:143)
org.apache.struts.action.RequestProcessor.processActionCreate(RequestProcessor.java:292)
org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:230)
org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196)
org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432)
javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
If anyone has any ideas it will be much appreciated
Thanks in Advance
Andy -
Complete working code for Gmail POP3 & SMTP with SSL - Java mail API
Finally, your code-hunt has come to an end!!!!
I am presenting you the complete solution (with code) to send and retrieve you mails to & from GMAIL using SMTP and POP3 with SSL & Authenticaion enabled. [Even starters & newbies like me, can easy try, test & understand - But first download & add JAR's of Java Mail API & Java Activation Framework to Netbeans Library Manager]
Download Java Mail API here
http://java.sun.com/products/javamail/
Read Java Mail FAQ's here
http://java.sun.com/products/javamail/FAQ.html
Download Java Activation Framework [JAF]
http://java.sun.com/products/javabeans/jaf/downloads/index.html
Also, The POP program retrieves the mail sent with SMTP program :) [MOST IMPORTANT & LARGELY IN DEMAND]okey.. first things first... all of your thanks goes to the following and not a s@!te to me :)
hail Java !!
hail Java mail API !!
hail Java forums !!
hail Java-tips.org !!
hail Netbeans !!
Thanks to all coders who helped me by getting the code to work in one piece.
special thanks to "bshannon" - The dude who runs this forum from 97!!I am just as happy as you will be when you execute the below code!! [my 13 hours of tweaking & code hunting has paid off!!]
Now here it is...I only present you the complete solution!!
START OF PROGRAM 1
SENDING A MAIL FROM GMAIL ACCOUNT USING SMTP [STARTTLS (SSL)] PROTOCOL OF JAVA MAIL APINote on Program 1:
1. In the code below replace USERNAME & PASSWORD with your respective GMAIL account username and its corresponding password!
2. Use the code to make your Gmail client [jsp/servlets whatever]
//Mail.java - smtp sending starttls (ssl) authentication enabled
//1.Open a new Java class in netbeans (default package of the project) and name it as "Mail.java"
//2.Copy paste the entire code below and save it.
//3.Right click on the file name in the left side panel and click "compile" then click "Run"
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class Main
String d_email = "[email protected]",
d_password = "PASSWORD",
d_host = "smtp.gmail.com",
d_port = "465",
m_to = "[email protected]",
m_subject = "Testing",
m_text = "Hey, this is the testing email.";
public Main()
Properties props = new Properties();
props.put("mail.smtp.user", d_email);
props.put("mail.smtp.host", d_host);
props.put("mail.smtp.port", d_port);
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.auth", "true");
//props.put("mail.smtp.debug", "true");
props.put("mail.smtp.socketFactory.port", d_port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
SecurityManager security = System.getSecurityManager();
try
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
//session.setDebug(true);
MimeMessage msg = new MimeMessage(session);
msg.setText(m_text);
msg.setSubject(m_subject);
msg.setFrom(new InternetAddress(d_email));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));
Transport.send(msg);
catch (Exception mex)
mex.printStackTrace();
public static void main(String[] args)
Main blah = new Main();
private class SMTPAuthenticator extends javax.mail.Authenticator
public PasswordAuthentication getPasswordAuthentication()
return new PasswordAuthentication(d_email, d_password);
END OF PROGRAM 1-----
START OF PROGRAM 2
RETRIVE ALL THE MAILS FROM GMAIL INBOX USING Post Office Protocol POP3 [SSL] PROTOCOL OF JAVA MAIL APINote:
1.Log into your gmail account via webmail [http://mail.google.com/]
2.Click on "settings" and select "Mail Forwarding & POP3/IMAP"
3.Select "enable POP for all mail" and "save changes"
4.In the code below replace USERNAME & PASSWORD with your respective GMAIL account username and its corresponding password!
PROGRAM 2 - PART 1 - Main.java
//1.Open a new Java class file in the default package
//2.Copy paste the below code and rename it to Mail.java
//3.Compile and execute this code.
public class Main {
/** Creates a new instance of Main */
public Main() {
* @param args the command line arguments
public static void main(String[] args) {
try {
GmailUtilities gmail = new GmailUtilities();
gmail.setUserPass("[email protected]", "PASSWORD");
gmail.connect();
gmail.openFolder("INBOX");
int totalMessages = gmail.getMessageCount();
int newMessages = gmail.getNewMessageCount();
System.out.println("Total messages = " + totalMessages);
System.out.println("New messages = " + newMessages);
System.out.println("-------------------------------");
//Uncomment the below line to print the body of the message. Remember it will eat-up your bandwidth if you have 100's of messages. //gmail.printAllMessageEnvelopes();
gmail.printAllMessages();
} catch(Exception e) {
e.printStackTrace();
System.exit(-1);
END OF PART 1
PROGRAM 2 - PART 2 - GmailUtilities.java
//1.Open a new Java class in the project (default package)
//2.Copy paste the below code
//3.Compile - Don't execute this[Run]
import com.sun.mail.pop3.POP3SSLStore;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.FetchProfile;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
import javax.mail.internet.ContentType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.ParseException;
public class GmailUtilities {
private Session session = null;
private Store store = null;
private String username, password;
private Folder folder;
public GmailUtilities() {
public void setUserPass(String username, String password) {
this.username = username;
this.password = password;
public void connect() throws Exception {
String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
Properties pop3Props = new Properties();
pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false");
pop3Props.setProperty("mail.pop3.port", "995");
pop3Props.setProperty("mail.pop3.socketFactory.port", "995");
URLName url = new URLName("pop3", "pop.gmail.com", 995, "",
username, password);
session = Session.getInstance(pop3Props, null);
store = new POP3SSLStore(session, url);
store.connect();
public void openFolder(String folderName) throws Exception {
// Open the Folder
folder = store.getDefaultFolder();
folder = folder.getFolder(folderName);
if (folder == null) {
throw new Exception("Invalid folder");
// try to open read/write and if that fails try read-only
try {
folder.open(Folder.READ_WRITE);
} catch (MessagingException ex) {
folder.open(Folder.READ_ONLY);
public void closeFolder() throws Exception {
folder.close(false);
public int getMessageCount() throws Exception {
return folder.getMessageCount();
public int getNewMessageCount() throws Exception {
return folder.getNewMessageCount();
public void disconnect() throws Exception {
store.close();
public void printMessage(int messageNo) throws Exception {
System.out.println("Getting message number: " + messageNo);
Message m = null;
try {
m = folder.getMessage(messageNo);
dumpPart(m);
} catch (IndexOutOfBoundsException iex) {
System.out.println("Message number out of range");
public void printAllMessageEnvelopes() throws Exception {
// Attributes & Flags for all messages ..
Message[] msgs = folder.getMessages();
// Use a suitable FetchProfile
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
folder.fetch(msgs, fp);
for (int i = 0; i < msgs.length; i++) {
System.out.println("--------------------------");
System.out.println("MESSAGE #" + (i + 1) + ":");
dumpEnvelope(msgs);
public void printAllMessages() throws Exception {
// Attributes & Flags for all messages ..
Message[] msgs = folder.getMessages();
// Use a suitable FetchProfile
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
folder.fetch(msgs, fp);
for (int i = 0; i < msgs.length; i++) {
System.out.println("--------------------------");
System.out.println("MESSAGE #" + (i + 1) + ":");
dumpPart(msgs[i]);
public static void dumpPart(Part p) throws Exception {
if (p instanceof Message)
dumpEnvelope((Message)p);
String ct = p.getContentType();
try {
pr("CONTENT-TYPE: " + (new ContentType(ct)).toString());
} catch (ParseException pex) {
pr("BAD CONTENT-TYPE: " + ct);
* Using isMimeType to determine the content type avoids
* fetching the actual content data until we need it.
if (p.isMimeType("text/plain")) {
pr("This is plain text");
pr("---------------------------");
System.out.println((String)p.getContent());
} else {
// just a separator
pr("---------------------------");
public static void dumpEnvelope(Message m) throws Exception {
pr(" ");
Address[] a;
// FROM
if ((a = m.getFrom()) != null) {
for (int j = 0; j < a.length; j++)
pr("FROM: " + a[j].toString());
// TO
if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
for (int j = 0; j < a.length; j++) {
pr("TO: " + a[j].toString());
// SUBJECT
pr("SUBJECT: " + m.getSubject());
// DATE
Date d = m.getSentDate();
pr("SendDate: " +
(d != null ? d.toString() : "UNKNOWN"));
static String indentStr = " ";
static int level = 0;
* Print a, possibly indented, string.
public static void pr(String s) {
System.out.print(indentStr.substring(0, level * 2));
System.out.println(s);
}END OF PART 2
END OF PROGRAM 2
P.S: CHECKING !!
STEP 1.
First compile and execute the PROGRAM 1 with your USERNAME & PASSWORD. This will send a mail to your own account.
STEP 2.
Now compile both PART 1 & PART 2 of PROGRAM 2. Then, execute PART 1 - Main.java. This will retrive the mail sent in step 1. njoy! :)
In future, I hope this is added to the demo programs of the Java Mail API download package.
This is for 3 main reasons...
1. To prevent a lot of silly questions being posted on this forum [like the ones I did :(].
2. To give the first time Java Mail user with a real time working example without code modification [code has to use command line args like the demo programs - for instant results].
3. Also, this is what google has to say..
"The Gmail Team is committed to making sure you always can access your mail. That's why we're offering POP access and auto-forwarding. Both features are free for all Gmail users and we have no plans to charge for them in the future."
http://mail.google.com/support/bin/answer.py?answer=13295
I guess bshannon & Java Mail team is hearing this....
Again, Hurray and thanks for helping me make it!! cheers & no more frowned faces!!
(: (: (: (: (: GO JCODERS GO!! :) :) :) :) :)
codeace
-----Thanks for the reply,
I did checked by enabling session debuging and also checked pop settings it's enabled for all
mails, I tried deleting some very old messages and now the message count is changed to 310.
This may be the problem with gmail.
Bellow is the output i got,
DEBUG: setDebug: JavaMail version 1.4ea
DEBUG: getProvider() returning javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc]
DEBUG POP3: connecting to host "pop.gmail.com", port 995, isSSL false
S: +OK Gpop ready for requests from 121.243.255.240 n22pf5432603pof.2
C: USER [email protected]
S: +OK send PASS
C: PASS my_password
S: +OK Welcome.
C: STAT
S: +OK 310 26900234
Custom output: messageCount : 310
C: QUIT
S: +OK Farewell. -
Using Java Mail in Tomcat via JNDI
I have a web application and I want to make use of JNDI Mail Sessions for sending email in my Web Appln.
I am using Tomcat4.0.1
In my server.xml file I declared a resource as follows:
<Resource name="mail/Session" auth="Container" type="javax.mail.Session"/>
<ResourceParams name="mail/Session">
<parameter>
<name>mail.smtp.host</name>
<value>mail.abc.com</value>
</parameter>
</ResourceParams>
Now Inside my jsp/servlet code i can use something like this:=
// Acquire our JavaMail session object
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
Session session = (Session) envCtx.lookup("mail/Session");
// Prepare our mail message
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
InternetAddress dests[] = new InternetAddress[]
{ new InternetAddress(to) };
message.setRecipients(Message.RecipientType.TO, dests);
message.setSubject(subject);
message.setContent(content, "text/plain");
// Send our mail message
Transport.send(message);
But my smtp mail provider uses Authentication.
So I am looking of some way wherein I can provide the user and password information in the server.xml file itself along with smtp provider.
My Query is How to do this as i dont see any references for using JavaMail sessions using Authentication
Any Help highly appreciated
Thanksfor the mail session I am getting an error like this
ENCOUNTERED EXCEPTION: javax.mail.SendFailedException: Sending failed; nested exception is: javax.mail.SendFailedException: Invalid Addresses; nested exception is: javax.mail.SendFailedException: 550 5.7.1 Unable to relay for [email protected]
javax.mail.SendFailedException: Sending failed;
nested exception is:
javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
javax.mail.SendFailedException: 550 5.7.1 Unable to relay for [email protected]
at javax.mail.Transport.send0(Transport.java:219)
at javax.mail.Transport.send(Transport.java:81)
at SendMailServlet.doPost(SendMailServlet.java:63)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:243)
at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:566)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:472)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:201)
at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:566)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:472)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943)
at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2344)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:566)
at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:170)
at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:564)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:170)
at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:564)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:462)
at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:564)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:472)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:163)
at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:566)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:472)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943)
at org.apache.catalina.connector.http.HttpProcessor.process(HttpProcessor.java:1011)
at org.apache.catalina.connector.http.HttpProcessor.run(HttpProcessor.java:1106)
at java.lang.Thread.run(Unknown Source) -
Java Mail...! Experts U have some work here
I am trying send mail from gmail account using the code below.
I have add mail.jar to my classpath, now the problem is my code
is successfully compiled, but generates a runtime error as below.
Any Experts.............??
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import java.io.*;
public class SendMailUsingAuthentication
private static final String SMTP_HOST_NAME = "smtp.gmail.com";
private static final String SMTP_AUTH_USER = "sss.sankar";
private static final String SMTP_AUTH_PWD = "*****";
private static final String emailMsgTxt = "Online Order ";
private static final String emailSubjectTxt = "Order Confirmation";
private static final String emailFromAddress = "[email protected]";
private static final String[] emailList = {"[email protected]"};
public static void main(String args[]) throws Exception
SendMailUsingAuthentication smtpMailSender = new SendMailUsingAuthentication();
smtpMailSender.postMail( emailList, emailSubjectTxt, emailMsgTxt,emailFromAddress);
System.out.println("Sucessfully Sent mail to All Users");
public void postMail( String recipients[ ], String subject,String message , String from) throws MessagingException
boolean debug = false;
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable","true");
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getDefaultInstance(props, auth);
session.setDebug(debug);
Message msg = new MimeMessage(session);
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++)
addressTo[i] = new InternetAddress(recipients);
msg.setRecipients(Message.RecipientType.TO, addressTo);
msg.setSubject(subject);
msg.setContent(message, "text/plain");
Transport.send(msg);
private class SMTPAuthenticator extends javax.mail.Authenticator
public PasswordAuthentication getPasswordAuthentication()
String username = SMTP_AUTH_USER;
String password = SMTP_AUTH_PWD;
return new PasswordAuthentication(username, password);
Error
=====
deps-jar:
Compiling 1 source file to C:\Documents and Settings\promise main\My Documents\NetBeansProjects\sankardemo\build\classes
compile-single:
run-single:
Exception in thread "main" javax.mail.MessagingException: Unknown SMTP host: smtp.gmail.com;
nested exception is:
java.net.UnknownHostException: smtp.gmail.com
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1389)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:412)
at javax.mail.Service.connect(Service.java:310)
at javax.mail.Service.connect(Service.java:169)
at javax.mail.Service.connect(Service.java:118)
at javax.mail.Transport.send0(Transport.java:188)
at javax.mail.Transport.send(Transport.java:118)
at SendMailUsingAuthentication.postMail(SendMailUsingAuthentication.java:52)
at SendMailUsingAuthentication.main(SendMailUsingAuthentication.java:20)
Caused by: java.net.UnknownHostException: smtp.gmail.com
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:177)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:519)
at java.net.Socket.connect(Socket.java:469)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:233)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1359)
... 8 more
Java Result: 1
BUILD SUCCESSFUL (total time: 3 seconds)MSSL wrote:
ya guy i understand that, but any idea about how to correct the same.Give it an smtp host that is reachable.
My guess is that you'll need to go through a proxy server, since I can rech that host just fine.
Or perhaps your DNS is boned. -
Unknown host or domain for exotic domain
Hello,
We are running this version :
Sun Java(tm) System Messaging Server 6.3-6.03 (built Mar 14 2008; 32bit)
libimta.so 6.3-6.03 (built 17:12:37, Mar 14 2008; 32bit)
When we try to send a mail for all +.me+ domain we have : +550 5.1.2 unknown host or domain: [email protected]+
We have this problem with this address for example : [email protected]
The dns resolution seems good on the server :
Non-authoritative answer:
ac.me preference = 10, mail exchanger = mail.ac.me
Authoritative answers can be found from:
ac.me nameserver = ns.ac.me
ac.me nameserver = ns2.ac.me
mail.ac.me internet address = 89.188.43.10
Is there a filter for some domains in any config file or an invalid domain list compiled in the binary ?
I don't have tried all the domain but it seems that we have the same problem with the +.cat+ domain.
Thank you
Edited by: kitegui on Nov 19, 2009 7:14 AM>
Is there a filter for some domains in any config file or an invalid domain list compiled in the binary ?
Known email domains are listed in the <msg_base>/config/internet.rules file.
The ".me" domain was added to the file in MS6.3 patch 30 and above. I suggest you use this as an opportunity to patch your system to the latest patch release.
I don't have tried all the domain but it seems that we have the same problem with the +.cat+ domain.The ".cat" domain was added to the file over three years ago.
Regards,
Shane. -
HI, Iam trying to Integrate Exchange server using Java Mail
Here is what iam stuck with, I have a problem while conneting to Exchange Server using imap over ssl.
My code looks like this
props.put("mail.imap.host",host);
props.put("mail.imap.sasl.authorizationid","user1");
props.put("mail.imap.sasl.enable","true");
props.setProperty("mail.imap.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.imap.socketFactory.fallback","true");
props.setProperty("mail.imap.socketFactory.port","993");
Authenticator auth = new myauthenticator(AdminUserName,AdminPassword);
Session session = Session.getInstance(props,auth);
session.setDubug(true);
Store store = session.getStore("imap");
store.connect();
I get the following Exception as
javax.mail.MessagingException: Software caused connection abort: recv failed;
nested exception is:
java.net.SocketException: Software caused connection abort: recv failed
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:571)
at javax.mail.Service.connect(Service.java:310)
at javax.mail.Service.connect(Service.java:169)
at javax.mail.Service.connect(Service.java:118)
at MoveCalendar.move(MoveCalendar.java:63)
at SendCalendar.send(SendCalendar.java:74)
at SendCalendar.main(SendCalendar.java:40)
Caused by: java.net.SocketException: Software caused connection abort: recv failed
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(Unknown Source)
at com.sun.net.ssl.internal.ssl.InputRecord.a(Unknown Source)
at com.sun.net.ssl.internal.ssl.InputRecord.read(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.a(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.j(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.a(Unknown Source)
at com.sun.net.ssl.internal.ssl.AppInputStream.read(Unknown Source)
at com.sun.mail.util.TraceInputStream.read(TraceInputStream.java:110)
at java.io.BufferedInputStream.fill(Unknown Source)
at java.io.BufferedInputStream.read(Unknown Source)
at com.sun.mail.iap.ResponseInputStream.readResponse(ResponseInputStream.java:97)
at com.sun.mail.iap.Response.<init>(Response.java:96)
at com.sun.mail.imap.protocol.IMAPResponse.<init>(IMAPResponse.java:61)
at com.sun.mail.imap.protocol.IMAPResponse.readResponse(IMAPResponse.java:135)
at com.sun.mail.imap.protocol.IMAPProtocol.readResponse(IMAPProtocol.java:261)
at com.sun.mail.iap.Protocol.<init>(Protocol.java:114)
at com.sun.mail.imap.protocol.IMAPProtocol.<init>(IMAPProtocol.java:104)
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:538)
... 6 more
DEBUG: setDebug: JavaMail version 1.4.1
DEBUG: getProvider() returning javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc]
DEBUG: mail.imap.fetchsize: 16384
DEBUG: enable SASL
DEBUG: mail.imap.sasl.authorizationid: user1
If i change the sessionFactory.class or if I remove this property I donot get any Exception It gets Executed well, but IT goes directly to the Adminstrators Mail account but not to the AuthorizationId I gave it. Can any one give me sugssion upon this issue.I don't understand whether the problem was with the Exchange Server I was trying to connect or with my local Environmenthi,
Iam very thankful for your reply here's the requested debug steps
DEBUG: setDebug: JavaMail version 1.4.1
DEBUG: getProvider() returning javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc]
DEBUG: mail.imap.fetchsize: 16384
DEBUG: enable SASL
DEBUG: mail.imap.sasl.authorizationid: user1
DEBUG: protocolConnect returning false, host=india.lendingspace.com, user=PMaganti, password=<null>
* OK Microsoft Exchange 2000 IMAP4rev1 server version 6.0.6249.0 (lsinmail.india.lendingspace.com) ready.
A0 CAPABILITY
* CAPABILITY IMAP4 IMAP4rev1 IDLE LOGIN-REFERRALS MAILBOX-REFERRALS NAMESPACE LITERAL+ UIDPLUS CHILDREN AUTH=NTLM
A0 OK CAPABILITY completed.
IMAP DEBUG: AUTH: NTLM
DEBUG: protocolConnect login, host=****, user=AdminUserName, password=<non-null>
IMAP SASL DEBUG: Mechanisms: NTLM
IMAP SASL DEBUG: No SASL support
A1 LOGIN AminUserName AdminPassword
A1 OK LOGIN completed.
A2 CAPABILITY
* CAPABILITY IMAP4 IMAP4rev1 IDLE LOGIN-REFERRALS MAILBOX-REFERRALS NAMESPACE LITERAL+ UIDPLUS CHILDREN AUTH=NTLM
A2 OK CAPABILITY completed.
IMAP DEBUG: AUTH: NTLM
DEBUG: connection available -- size: 1
A3 SELECT INBOX
* 1 EXISTS
* 1 RECENT
* FLAGS (\Seen \Answered \Flagged \Deleted \Draft $MDNSent)
* OK [PERMANENTFLAGS (\Seen \Answered \Flagged \Deleted \Draft $MDNSent)] Permanent flags
* OK [UNSEEN 1] Is the first unseen message
* OK [UIDVALIDITY 261914] UIDVALIDITY value
A3 OK [READ-WRITE] SELECT completed.
No of Messages msgs 1
A4 FETCH 1 (ENVELOPE INTERNALDATE RFC822.SIZE)
* 1 FETCH (ENVELOPE ("5 Mar 2009 13:25:19 +0530" "Outlook Calendar Events Using Java" ((NIL NIL "XXXXX" "XXXXX")) ((NIL NIL "XXXXX" "XXXXX")) ((NIL NIL "XXXXX" "XXXXX")) ((NIL NIL "XXXX" "XXXX")) NIL NIL NIL "<XXXXX>") INTERNALDATE " 5-Mar-2009 13:25:19 +0530" RFC822.SIZE 1348)
A4 OK FETCH completed.
FROM: XXXX
SUBJECT: Outlook Calendar Events Using Java
DATE: Thu Mar 05 13:25:19 IST 2009
A5 FETCH 1 (BODYSTRUCTURE)
* 1 FETCH (BODYSTRUCTURE (("TEXT" "CALENDAR" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 598 10 NIL NIL NIL) "mixed" ("boundary" "----=_Part_0_18680399.1236239719654") NIL NIL))
A5 OK FETCH completed.
[ Multipart Message ]
CONTENT:TEXT/CALENDAR; charset=US-ASCII
A6 STORE 1 +FLAGS (\Answered)
* 1 FETCH (FLAGS (\Answered \Recent))
A6 OK STORE completed.
A7 COPY 1 CALENDAR
A7 OK [COPYUID 262745 258 23] COPY completed, 1 messages copied.
A8 EXAMINE INBOX
* 1 EXISTS
* 0 RECENT
* FLAGS (\Seen \Answered \Flagged \Deleted \Draft $MDNSent)
* OK [PERMANENTFLAGS ()] Permanent flags
* OK [UNSEEN 1] Is the first unseen message
* OK [UIDVALIDITY 261914] UIDVALIDITY value
A8 OK [READ-ONLY] EXAMINE completed.
A9 CLOSE
A9 OK CLOSE completed.
DEBUG: added an Authenticated connection -- size: 1
A10 LOGOUT
* BYE Microsoft Exchange 2000 IMAP4rev1 server version 6.0.6249.0 signing off.
A10 OK LOGOUT completed.
DEBUG: IMAPStore connection dead
DEBUG: IMAPStore cleanup, force false
DEBUG: IMAPStore cleanup done
Actually what iam doing is read a mail which was more recent in inbox and If it is an Calendar event Iam copying that mail to Calendar Folder. So that Microsoft OUTLOOK automatically recongnizes them and secudles them in it's Calendars
This is actually done for adminstrator's Account but not for the user1
As you have suggested I removed the socketFactory class stuff and did this.
and this is my modified Code
props.put("mail.imap.host",imapHost);
props.put("mail.imap.sasl.enable", "true");
props.put("mail.imap.sasl.authorizationid", "user1");
Authenticator auth=new myauthentication(imapUserName,imapPassword);
Session session = Session.getInstance(props,auth);
session.setDebug(true);
store = session.getStore("imap");
store.connect();
And that goes like that. -
HI TO ALL......
I AM NEW TO THIS FIELD....I AM TRYING TO SEND EMAIL THROUGH JAVA MAIL FUNCTION......,FIRST I AM FETCHING THE MAIL ADDRESS FROM DATA BASE.....I WANT TO SEND MAIL TO THOSE ADDRESS......HERE I M LITTLE BIT CONFUSED....PLZ HELP ME....BELOW IS THE CODE.........
THIS FOR SEARCHING THE MAIL IDS......(SearchEmail .java)
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.sql.*;
public class SearchEmail extends HttpServlet {
public String s1;
public String username="root";
public String passWord="";
public String url="jdbc:mysql://192.168.0.7:3306/ias";
private String SUB_NO="";
private String ST_DT="";
private String EMAIL="";
public void init() {
try {
Class.forName("sun.mysql.Jdbc.Driver");
System.out.println("JDBC driver loaded");
catch (ClassNotFoundException e) {
System.out.println(e.toString());
/**Process the HTTP Get request*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
sendPageHeader(response);
sendSearchForm(response);
sendPageFooter(response);
/**Process the HTTP Post request*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ST_DT = request.getParameter("ST_DT");
sendPageHeader(response);
sendSearchForm(response);
sendSearchResult(response);
sendPageFooter(response);
public void sendSearchResult(HttpServletResponse response)
throws IOException {
PrintWriter out = response.getWriter();
try {
Connection con = DriverManager.getConnection(url,username,passWord);
System.out.println("got connection");
Statement s = con.createStatement();
String sql= "SELECT EMAIL " + "FROM temp "+
"WHERE ST_DT='" + ST_DT + "' AND EMAIL!='" + null + "'";
ResultSet rs = s.executeQuery(sql);
StringBuffer sb = new StringBuffer(100);
while (rs.next()) {
String SUB_NO = rs.getString(1);
s1 =sb.append( rs.getString(1)).append(",").toString();
out.println("<TABLE border='1'>");
out.println("<TR>");
out.println("<TD>TO</TD><TD><INPUT TYPE=TEXT SIZE='50' VALUE='"+ s1 +"' ></TD>");
out.println("</TR>");
out.println("<TR>");
out.println("<TD>FROM</TD><TD><INPUT TYPE=TEXT SIZE='50' [email protected] ></TD>");
out.println("</TR>");
out.println("</TR>");
out.println("<TD>SUBJECT</TD><TD><INPUT TYPE=TEXT SIZE='50' NAME=SUBJECT></TD>");
out.println("</TR>");
out.println("<TR>");
out.println("<TD>MESSAGE </TD><td><textarea cols='70' rows='20' name='MESSAGE'>");
out.println("C.Vedamurthy senior");
out.println("Administrative Assistant");
out.println("Indian Academy of Sciences");
out.println("C.V.Raman Avenue,Near Mekhri Circle");
out.println("Post Box No 8005,sadashivanagar'");
out.println("bangalore 560080");
out.println("office no 23612546,23611034,23612943 extn 207 ");
out.println("res 23431357;Fax 23616094;");
out.println("</textarea></td>");
out.println("</TR>");
out.println("<table align='center'>");
out.println("<TR>");
out.println("<form action='mailservlet' method='post' name='myform'>");
out.println("<CENTER> <TD><INPUT TYPE='SUBMIT' VALUE='send'></INPUT></TD></CENTER>");
out.println("</form>");
out.println("</TR>");
out.println("</TABLE>");
rs.close();
s.close();
con.close();
catch (SQLException e) {
catch (Exception e) {
out.println("</TABLE>");
* Send the HTML page header, including the title
* and the <BODY> tag
private void sendPageHeader(HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>Displaying Selected Record(s)</TITLE>");
out.println("</HEAD>");
out.println("<BODY BGCOLOR=#FFE4C4>");
out.println("<CENTER>");
* Send the HTML page footer, i.e. the </BODY>
* and the </HTML>
private void sendPageFooter(HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("</CENTER>");
out.println("</BODY>");
out.println("</HTML>");
/**Send the form where the user can type in
* the details for a new user
private void sendSearchForm(HttpServletResponse response)
throws IOException {
PrintWriter out = response.getWriter();
out.println("<BR><H2>Search</H2>");
out.println("<BR>");
out.println("<BR><FORM METHOD=POST>");
out.print("START DATE: <INPUT TYPE=TEXT Name=ST_DT");
out.print(" VALUE=\"" + ST_DT + "\"");
out.println(">");
out.println("<BOTTOM>");
out.println("<TABLE ALIGN='CENTER'>");
out.println("<INPUT TYPE=SUBMIT VALUE=submit>");
out.println("</TABLE>");
out.println("</FORM>");
THIS IS JAVA MAIL FUNCTION.........(mailservlet .java)
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*; // important
import javax.mail.event.*; // important
import java.net.*;
import java.util.*;
import javax.mail.MessagingException;
public class mailservlet extends HttpServlet
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
PrintWriter out=response.getWriter();
response.setContentType("text/html");
try
Properties props=new Properties();
props.put("mail.smtp.host","localhost"); // 'localhost' for testing
Session session1 = Session.getDefaultInstance(props,null);
String s1 = request.getParameter("FROM"); //sender (from)
String s2 = request.getParameter("EMAIL");
String s3 = request.getParameter("SUBJECT");
String s4 = request.getParameter("MESSAGE");
Message message =new MimeMessage(session1);
message.setFrom(new InternetAddress(s1));
message.setRecipients
(Message.RecipientType.TO,InternetAddress.parse(s2,false));
message.setSubject(s3);
message.setText(s4);
Transport.send(message);
out.println("mail has been sent");
catch(Exception ex)
out.println("COULD NOT SEND EMAIL.....");
plz help me its very urgent ........out.println("<TD>TO</TD><TD><INPUT TYPE=TEXT SIZE='50' VALUE='"+ s1 +"' ></TD>");
out.println("</TR>");
out.println("<TR>");
out.println("<TD>FROM</TD><TD><INPUT TYPE=TEXT SIZE='50' VALUE=[email protected] ></TD>");
You didn't put names to those fields above:
out.println("<TD>TO</TD><TD><INPUT TYPE=TEXT SIZE='50' VALUE='"+ s1 +"' name ='EMAIL'></TD>");
out.println("</TR>");
out.println("<TR>");
out.println("<TD>FROM</TD><TD><INPUT TYPE=TEXT SIZE='50' VALUE='[email protected]' name='FROM'></TD>");also try:
catch(Exception ex)
out.println("COULD NOT SEND EMAIL.....");
ex.printStackTrace();
}to know what is exactly the error. -
Java mail api - sending mails to gmail account
Hello
I am using java mail api to send mails.when i send mails to gmail from ids which are not in gmail friends list, most of the mails are going to spam.Ofcourse, some of them go to inbox.I tried in lot of ways to analyse the problem.But nothing could help. Can anyone plzz tell me how to avoid mails going to spam in gmail, using java mail api?
Thank you in advance,
Regards,
Aradhana
Message was edited by:
Aradhanaam using the below code.
Properties props = System.getProperties();
// Setup mail server
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.port","25");
props.put("mail.smtp.auth", isAuth);
Authenticator auth = new UserAuthenticator();
// Get session
Session s = Session.getDefaultInstance(props,auth);
// Define message
Message m = new MimeMessage(s);
// setting message attributes
try {
m.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
InternetAddress f_addr=new InternetAddress(from);
f_addr.setPersonal(personalName);
m.setFrom(f_addr);
m.setSubject(subject);
m.setSentDate(new Date());
m.setContent(msg,"text/plain");
m.saveChanges();
// send message
Transport.send(m);
Message was edited by:
Aradhana -
Save Attachment from exchange server 2010 from oracle using java mail API
Hello,
I want to read email from microsoft exchangeserver 2010 and save attachement into a folder.I created an Java program to import attachments from a exchange server mailbox using "POP3S".It works fine when run as a java application.But when i put this inside Oracle11g R2 using load java and while executing from a procedure it gives an error at parsing message into Multipart
Error at line : Multipart mp = (Multipart)m.getContent();
Error:
Content-Type: multipart/mixed;
boundary="_002_A0C2E09A..................................."
java.lang.ClassCastException
at mailPop3.checkmail(mailPop3:71)
My Java Class is as follows,
import java.io.*;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Date;
The function i used to check for attachments is given below.
public static boolean hasAttachments(Message m) throws java.io.IOException, MessagingException
Boolean hasAttachments = false;
try
// if it is a plain/html text - no attachements
if (m.isMimeType("text/*"))
return hasAttachments;
else if (m.isMimeType("multipart/alternative"))
return hasAttachments;
else if (m.isMimeType("multipart/*"))
Multipart mp = (Multipart)m.getContent();
if (mp.getCount() > 1)
hasAttachments = true;
return hasAttachments;
catch (Exception e) {
e.printStackTrace();
} finally {
return hasAttachments;
My Java Details as follows
java Version :1.5.0_10
java.vm.specification.version:1.0
java.vm.version :1.5.0_01
java.specification.version:1.5
java.class.version:48.0
Java mail API:javamail-1.4.4
Used Jars:mail.jar
Could someone explain why I am getting this error? What can I do to resolve this error?
Is any other Jar need other than mail.jar?
Any help would be much appreciated.
Regards,
NisanthHai EJP,
Thanks for your reply,
My full java class as follows,
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Part;
import javax.mail.Multipart;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeMessage;
public class Newmail
public Newmail()
super();
public static int mailPOP3(String phost,
String pusername,
String ppassword)
Folder inbox =null;
Store store =null;
int result = 1;
try
String host=phost;
final String username=pusername;
final String password=ppassword;
System.out.println("Authenticator");
Authenticator auth=new Authenticator()
protected PasswordAuthentication getPasswordAuthentication()
return new PasswordAuthentication(username, password);
System.out.println("Certificate");
String filename="D:\\Certi\\jssecacerts";
String password2 = "changeit";
System.setProperty("javax.net.ssl.trustStore",filename);
System.setProperty("javax.net.ssl.trustStorePassword",password2);
Properties props = System.getProperties();
System.out.println("host-----"+props);
props.setProperty("mail.pop3s.port", "993");
props.setProperty("mail.pop3s.starttls.enable","true");
props.setProperty("mail.pop3s.ssl.trust", "*");
Session session = Session.getInstance(props,auth);
session.setDebug(true);
store = session.getStore("pop3s");
System.out.println("store------"+store);
store.connect(host,username,password);
System.out.println("Connected...");
inbox = store.getDefaultFolder().getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Message[] msgs = inbox.getMessages();
System.out.println("msgs.length-----"+msgs.length);
result = 0;
int no_of_messages = msgs.length;
for ( int i=0; i < no_of_messages; i++)
System.out.println("msgs.count-----"+i);
System.out.println("Attachment....>"+msgs.getContentType());
Multipart mp = (Multipart)msgs[i].getContent();
System.out.println("Casting Success" + mp.getContentType());
catch(Exception e)
e.printStackTrace();
finally
try
if(inbox!=null)
inbox.close(false);
if(store!=null)
store.close();
return result;
catch(Exception e)
e.printStackTrace();
return result;
Please check it
Regards,
Nisanth -
Exception in java mail API when parsing email
I am receiving the following exception when receiving some emails that contain attachments with java mail (irrelevant part of stack trace omitted):
javax.mail.internet.ParseException: Expected ';', got ","
at javax.mail.internet.ParameterList.<init>(ParameterList.java:289)
at javax.mail.internet.ContentDisposition.<init>(ContentDisposition.java:100)
at javax.mail.internet.MimeBodyPart.getFileName(MimeBodyPart.java:1136)
The header of a message the causes the problem is:
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) ------------ Message headers ------------
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) Received: from mail2.uscourts.gov ([10.170.250.2])
by ushub06.uscmail.dcn (Lotus Domino Release 8.5.2FP1 HF3)
with SMTP id 2011042514392620-733724 ;
Mon, 25 Apr 2011 14:39:26 -0400
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) Received: from (unknown [63.174.91.123]) by avms-usc-04c-02vh.ibmta.uscourts.gov with smtp
id 191c_067d_57fad3b8_6f6b_11e0_8de9_00265519f638;
Mon, 25 Apr 2011 18:39:24 +0000
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) X-WSS-ID: 0LK815L-05-67D-02
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) X-M-MSG:
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) Received: from kcmexclaim.Our-Firm.com (unknown [10.42.5.222])by mail4.stinson.com (Axway MailGate 3.8.1) with ESMTP id 27239A12C1D; Mon, 25 Apr 2011 13:39:20 -0500 (CDT)
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) Received: from KCME2K7-HUB02.Our-Firm.com ([10.42.5.19]) by kcmexclaim.Our-Firm.com with Microsoft SMTPSVC(6.0.3790.4675); Mon, 25 Apr 2011 13:39:23 -0500
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) Received: from FIRMCMS01.Our-Firm.com ([fe80::81d0:dd2b:9983:1126]) by KCME2K7-HUB02.Our-Firm.com ([::1]) with mapi; Mon, 25 Apr 2011 13:39:22 -0500
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) From:
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) To:
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) Cc:
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) Disposition-Notification-To:
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) Date: Mon, 25 Apr 2011 13:39:21 -0500
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) Subject: Order Regarding Application To Employ SMH as Debtor's Counsel
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) Thread-Topic: Order Regarding Application To Employ SMH as Debtor's Counsel
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) Thread-Index: AcwDb/bpRQlxt/eTQC6BA7G10hdWJQAB99vQ
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) Message-ID: <[email protected]>
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) Accept-Language: en-US
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) X-MS-Has-Attach: yes
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) X-MS-TNEF-Correlator:
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) acceptlanguage: en-US
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) Importance: Normal
2011-04-25 14:39:48,061 INFO [STDOUT] (WorkManager(2)-97) Priority: normal
2011-04-25 14:39:48,061 INFO [STDOUT] (WorkManager(2)-97) X-MimeOLE: Produced By Microsoft MimeOLE V6.00.3790.4841
2011-04-25 14:39:48,061 INFO [STDOUT] (WorkManager(2)-97) MIME-Version: 1.0
2011-04-25 14:39:48,061 INFO [STDOUT] (WorkManager(2)-97) Return-Path:
2011-04-25 14:39:48,061 INFO [STDOUT] (WorkManager(2)-97) X-OriginalArrivalTime: 25 Apr 2011 18:39:23.0526 (UTC) FILETIME=[18E10260:01CC0378]
2011-04-25 14:39:48,061 INFO [STDOUT] (WorkManager(2)-97) X-MIMETrack: Itemize by SMTP Server on USHUB06/H/US/USCOURTS(Release 8.5.2FP1 HF3|December 21, 2010) at 04/25/2011 02:39:26 PM, Serialize by POP3 Server(Release 8.0.2FP3 HF28|December 28, 2009) at 04/25/2011 02:39:47 PM
2011-04-25 14:39:48,061 INFO [STDOUT] (WorkManager(2)-97) Content-Transfer-Encoding: 7bit
2011-04-25 14:39:48,061 INFO [STDOUT] (WorkManager(2)-97) Content-Class: urn:content-classes:message 2011-04-25 14:39:48,061 INFO [STDOUT] (WorkManager(2)-97) Content-Type: multipart/mixed; boundary="_004_52835C1F7A6C8D4F989C433DCC611CA06F252D6682FIRMCMS01OurF_"
2011-04-25 14:39:48,061 INFO [STDOUT] (WorkManager(2)-97) Content-Language: en-US
the client/OS combination of the mail sender is Windows XP service Pack 3/Outlook 2007 , Java Mail version 1.4.3
Any help would be appreciated
Edited by: 854778 on Apr 26, 2011 8:28 AMThe exception is occurring when parsing the Content-Disposition header.
I don't see that header in the list of headers you provided.
Can you save the entire message to a text file using
msg.writeTo(new FileOutputStream("msg.txt"));
Then look for the Content-Disposition header in msg.txt. Most likely you'll
find that it is incorrectly formatted - as the exception says, there's a comma
in a place that a semicolon is expected.
Maybe you are looking for
-
firefox won't launch, and the above error message appears.
-
Problems with Fujifilm XD cards
Hi everyone! I recently moved to my first Mac, and have been slowly introducing various peripherals, including my much-loved Fujifilm F30 camera. While I haven't had many problems with the changeover, the F30 is proving a major stumbling point. Could
-
CX_SY_CONVERSION_NO_NUMBER
Hi, I´m trying to prin a Form and it throws the following dump: An exception occurred that is explained in detail below. The exception, which is assigned to class 'CX_SY_CONVERSION_NO_NUMB caught in
-
File structure access and default settings issues
Hello there, I have a MBP running 10.6.6 I noticed that, in the get info window for all my folders and files on the mac, at the bottom it has three users: me, staff, and everyone. And by default it seems to grant all users read rights. I have only tw
-
White Space at the top of Report output in Portal
Hi, I am running a Report in Portal through WAD template. in Report output a big white space comes at the top (almost half a page) and below that report result is shown. I want to remove that space (report result should start from top) I tried to che