Message.RecipientType.TO
hi,
i am facing problem in using Message.RecipientType.TO
for multiple recipients.i am using
Address[] address= (Address[])InternetAddress.parse(JTTo.getText().trim());
message.setRecipients(Message.RecipientType.TO,address);
JTTo.getText() will return To address string seperated by comma's.
this is urgent.
thanks for reply.
hi all,
actually i only made mistake in my code.Plesae ignore this topic.
thanking you.
Similar Messages
-
Javax.mail.message.recipienttype not found
Hi,
I use jdev10g and i want to send a mail message.
Here's a little snip of my class for sending a mail.
Jdeveloper gives me a error about Message.RecipientType.TO.
"Member 'RecipientType' not found in javax.mail.Message"
import javax.mail.Message;
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
I've installed the javamail-1.1.3 API.
In my project properties -> libraries, i've added this library with the correct path to the jar file.
I'm sure that this API have this Message class.
What is going wrong, have i missed something ???
Greetings,
PeterHi! Srikanth,
1. I checked MailerEJB.deploy under "Dependency Analyzer",
I checked activation.jar and mail.jar under the J2EE node.
I did the same for the MailerJSP.deploy.
2. I used same jdeveloper version and jdk 1.3.1_06.
3. I did a clean deploy for the ejb and mailerjsp.deploy
4. I recompiled and run the jpr,
from the message window, I got:
C:\jdeveloper\jdk\bin\javaw.exe -ojvm -classpath C:\oc4j\samples\ejb\EJBCallsJSP\classes;C:\oc4j\samples\ejb\EJBCallsJSP;C:\jdeveloper\jdev\lib\jdev-rt.jar;C:\jdeveloper\j2ee\home\lib\activation.jar;C:\jdeveloper\j2ee\home\lib\ejb.jar;C:\jdeveloper\j2ee\home\lib\jaas.jar;C:\jdeveloper\j2ee\home\lib\jaxp.jar;C:\jdeveloper\j2ee\home\lib\jcert.jar;C:\jdeveloper\j2ee\home\lib\jdbc.jar;C:\jdeveloper\j2ee\home\lib\jms.jar;C:\jdeveloper\j2ee\home\lib\jndi.jar;C:\jdeveloper\j2ee\home\lib\jnet.jar;C:\jdeveloper\j2ee\home\lib\jsse.jar;C:\jdeveloper\j2ee\home\lib\jta.jar;C:\jdeveloper\j2ee\home\lib\mail.jar;C:\jdeveloper\j2ee\home\oc4j.jar;C:\jdeveloper\jdbc\lib\classes12.jar;C:\jdeveloper\jdbc\lib\nls_charset12.jar oracle.otnsamples.ejbcallsjsp.mailclient.MailClientSample
I didn't see any error from this message window.
5. The no provider for smtp error is prompted from the mail client.
From above settings and running the application, I couldn't figure out where the error was coming from ?
Thanks
David -
I have had success in one of my servlets using JavaMail. I was able to send an email to my inbox to test it out. I proceeded to create another servlet based on that 1st one, and for reasons I can't explain, the servlet won't compile.
I get this error.
cannot resolve symbol :
variable : RecipientType
location : java.lang.String
msg.setRecipient(Message.RecipientType.TO, to); I get the same error when I switch out setRecipient for addRecipient.
However, through further testing, I've found that not only does my 1st servlet still compile, but I'm also able to run the code from the 2nd servlet, successfully in a JSP page. This is driving me nuts...how could there be a problem compiling? There's no reason why one servlet compiles (with similar if not almost exactly the same code) and the other won't. Plus this runs fine in a JSP page...what's going on??? I've spent hours on this and I can't figure it out...please help, any input is appreciated.
Here is the JSP page that runs successfully :
<%@page import="java.io.*"%>
<%@page import="java.util.Properties"%>
<%@page import="javax.mail.*"%>
<%@page import="javax.mail.Message.RecipientType"%>
<%@page import="javax.mail.internet.*"%>
<%@page import="javax.servlet.*"%>
<%@page import="javax.servlet.http.*"%>
<%@page import="javax.naming.*"%>
<%@page import="javax.sql.*"%>
<%@page import="java.sql.*"%>
<%
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Context ctx = new InitialContext();
if(ctx == null )
throw new Exception("Boom - No Context");
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/myDB");
conn = ds.getConnection();
stmt = conn.createStatement();
//get the POP3 and SMTP property values from db
rs = stmt.executeQuery("Select Tech_Support_Email, POP3, SMTP from sitewide_info");
String hostemailaddress = "";
String POP3 = ""; //mail.smtp.host, this one 1st
String SMTP = ""; //smtp.stratos.net, this one 2nd
if(rs.next()) {
hostemailaddress = rs.getString(1);
POP3 = rs.getString(2);
SMTP = rs.getString(3);
// Specify the SMTP Host
Properties props = new Properties();
//POP3 = mail.smtp.host & SMTP = smtp.stratos.net - must be in this order
props.put(POP3, SMTP);
// Create a mail session
Session ssn = Session.getDefaultInstance(props, null);
ssn.setDebug(true);
String subject = "Testing out Email";
String body = "hello";
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
rs = stmt.executeQuery("Select Customer_Name, Email_Address from customer_profiles where "
+"Customer_Number=1111");
String fromName = "";
String fromEmail = "";
if(rs.next()) {
fromName = rs.getString(1);
fromEmail = rs.getString(2);
InternetAddress from = new InternetAddress(fromEmail,fromName);
String toName = "Bob";
InternetAddress to = new InternetAddress(hostemailaddress,toName);
// Create the message
Message msg = new MimeMessage(ssn);
msg.setFrom(from);
msg.addRecipient(Message.RecipientType.TO, to);
msg.setSubject(subject);
msg.setContent(body, "text/html");
Transport.send(msg);
}//try
catch (MessagingException mex) {
mex.printStackTrace(); }
catch(Exception e) {}
finally {
try {
if (rs!=null) rs.close();
catch(SQLException e){}
try {
if (stmt!=null) stmt.close();
catch(SQLException e){}
try {
if (conn!=null) conn.close();
catch(SQLException e){}
}//finally
%>
Here's the servlet that won't compile :
package testing.servlets.email;
import java.io.*;
import java.util.Properties;
import javax.mail.*;
import javax.mail.Message.RecipientType;
import javax.mail.internet.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.naming.*;
import javax.sql.*;
import java.sql.*;
public class MessageCenterServlet extends HttpServlet {
public Connection conn = null;
public Statement stmt = null;
public Statement stmt2 = null;
public ResultSet rs = null;
public ResultSet rss = null;
public PrintWriter out = null;
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
doPost(req,res);
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
try {
out = res.getWriter();
Context ctx = new InitialContext();
if(ctx == null )
throw new Exception("Boom - No Context");
DataSource ds =
(DataSource)ctx.lookup(
"java:comp/env/jdbc/myDB");
conn = ds.getConnection();
stmt = conn.createStatement();
stmt2 = conn.createStatement();
HttpSession session = req.getSession();
String Subject = (String)session.getAttribute("Subject");
String Message = (String)session.getAttribute("Message");
sendAnEmail(rs,stmt,Subject,Message,res);
}//try
catch (Exception e) { }
finally { cleanup(rs,rss,stmt,stmt2,conn); }
}//post
public void cleanup(ResultSet r, ResultSet rs, Statement s, Statement s2, Connection c){
try {
if (r!=null) r.close();
catch(SQLException e){}
try {
if (rs!=null) rs.close();
catch(SQLException e){}
try {
if (s!=null) s.close();
catch(SQLException e){}
try {
if (s2!=null) s2.close();
catch(SQLException e){}
try {
if (c!=null) c.close();
catch(SQLException e){}
}//cleanUp
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public void sendAnEmail(ResultSet rs, Statement stmt, String Subject,String Message, HttpServletResponse res) {
try {
//get the POP3 and SMTP property values from db
rs = stmt.executeQuery("Select Tech_Support_Email, POP3, SMTP from sitewide_info");
String hostemailaddress = "";
String POP3 = "";
String SMTP = "";
if(rs.next()) {
hostemailaddress = rs.getString(1);
POP3 = rs.getString(2);
SMTP = rs.getString(3);
// Specify the SMTP Host
Properties props = new Properties();
props.put(POP3, SMTP);
// Create a mail session
Session ssn = Session.getDefaultInstance(props, null);
ssn.setDebug(true);
String subject = "Testing out Email";
String body = "hello";
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
rs = stmt.executeQuery("Select Customer_Name, Email_Address from customer_profiles where "
+"Customer_Number=1111");
String fromName = "";
String fromEmail = "";
if(rs.next()) {
fromName = rs.getString(1);
fromEmail = rs.getString(2);
InternetAddress from = new InternetAddress(fromDealerEmail,fromDealerName);
String toName = "Bob";
InternetAddress to = new InternetAddress(hostemailaddress,toName);
// Create the message
Message msg = new MimeMessage(ssn);
msg.setFrom(from);
msg.setRecipient(Message.RecipientType.TO, to);
msg.setSubject(subject);
msg.setContent(body, "text/html");
Transport.send(msg);
}//try
catch (MessagingException mex) {
mex.printStackTrace(); }
catch(Exception e) {}
}//end
}//class -Love2Java
Edited by: Love2Java on Mar 11, 2008 9:15 PMI have similar problem
I have the below code in Eclipse and I was able to compile and run it and everything works fine...
but I have code over in Oracle Jdev and jdev is complaining that "Message.RecipientType.TO" is not found....
I do have all the jars in the class path.... can't figure out what's wrong
can some one plz help me out.
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
public void postMail( String recipients, String subject,
String message , String from) throws MessagingException
boolean debug = false;
//Set the host smtp address
Properties props = new Properties();
props.put("mail.smtp.host", "server");
props.put("mail.smtp.auth", "true");
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getDefaultInstance(props, auth);
session.setDebug(debug);
// create a message
Message msg = new MimeMessage(session);
// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients, false));
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/plain");
Transport.send(msg);
private class SMTPAuthenticator extends javax.mail.Authenticator
public PasswordAuthentication getPasswordAuthentication()
String username ="user";
String password = "pass";
return new PasswordAuthentication(username, password);
} -
Message.RecipientType question
Hey All, running a program that fires of mails. I have to, from, cc, subject, and the message as defined values.
If I send an e-mail to distinct person 1 and cc distinct person 2 each get their mails. If the way the program executes, distinct person 1 is the "to" and that same person is the "cc" field, then that person only gets 1 total email. I keep thinking they should recieve two mails.
So in situation 1:
to: [email protected]
cc: [email protected]
both get mails.
In situation 2:
to: [email protected]
cc: [email protected]
[email protected] only recieves one mail.
Is this intentional of javamail or am I missing something completely.Hi sjtsjt,
If you send an email to a person and CC the same person, the person will only received one mail, This has nothing to do with the code but with the mail server.
I hope this answer your question.
Jmaritz -
Error trying to send email -- IOException while sending message
Email is successful when:
I run my application through JDeveloper
or
when I use a classpath, but if I try to execute app via a jar file, i get the following error message: IOException while sending message.
The jar file does include mail.jar and activation.jar.
Below is my email code:
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class JMAR_Mail {
private String sendTo;
private String sentFrom;
private String host;
private String messageSubject;
private String messageText;
private MimeMessage msg;
public JMAR_Mail() {}
public JMAR_Mail(String sendTo, String sentFrom, String _host) {
sendTo = _sendTo;
sentFrom = _sentFrom;
host = _host;
public void setEmailSubject(String _messageSubject) {
messageSubject = _messageSubject;
} // end setEmailSubject
public void setEmailText(String _text) {
messageText = _text;
public void sendEmail() throws MessagingException {
// create some properties and get the default Session
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
Session session = Session.getInstance(props, null);
InternetAddress addr = new InternetAddress();
// parses comma separted list of email addresses
InternetAddress[] address = addr.parse(sendTo);
msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(sentFrom));
msg.setSubject(messageSubject);
msg.setText(messageText);
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSentDate(new Date());
Transport.send(msg);
} // end sendEmail
}You don't want to include those jar files in your jar file,
you want to reference them:
http://forum.java.sun.com/thread.jspa?forumID=43&threadID=762763 -
Sending a message to fax using JavaMail
Hello all,
we are trying to create a system to send messages. The input will come from an Oracle 9i (9.0.2) database, our goal is to create email messages which can either be delivered to an email address or to a fax number.
The systems works if all addresses are regular email adresses, but we get the following message when using a fax number :javax.mail.internet.AddressException: Illegal route-addr in string ``fax:[email protected]''
I have already change the parse-method to parseHeader with the parseOption false, so that the addresses are not controlled against the standard. I expect the ':' (colon) in fax:012345678 is the cause of our problem, replacing it with a random character returns a 'normal' error message for a non-existing address.
I have included the log message with the exception, the sourcecode of our SendMailTest and the source of SendMail.
Is there any work around to this colon, so we can send faxes as well as emails.
Kind regards,
Nemata
log message----------------------------------------------------
C:\ProgramFiles\jdevstudio1013\jdk\bin\javaw.exe -ojvm -classpath C:\ProgramFiles\jdevstudio1013\jdev\mywork\ocbs\Client\classes;C:\ProgramFiles\jdevstudio1013\j2ee\home\lib;C:\ProgramFiles\jdevstudio1013\j2ee\home\lib\mail.jar;C:\ProgramFiles\jdevstudio1013\j2ee\home\lib\activation.jar com.vdscomputing.carpinvest.ocbs.db.io.SendMailTest
Constructor entered
return from constructor
com.vdscomputing.carpinvest.ocbs.db.io.SendMail@a Hello
javax.mail.internet.AddressException: Illegal route-addr in string ``fax:[email protected]''
message sent
Process exited with exit code 0.
source SendMailTest-------------------------------------
package com.vdscomputing.carpinvest.ocbs.db.io;
//class designed to test SendMail
public class SendMailTest {
public static void main( String args[]) {
String SMTPserver = "192.168.1.23";
String SMTPport = "25";
String Sender = "[email protected]";
String Recipient ="fax:[email protected]";
String CcRecipient = "[email protected]";
String BccRecipient = "";
String Subject = "faxinationTest";
String Body = "test mail 12 from test class";
String[] ErrorMessage = new String[1];
String Attachments ="";
// create mesage and monitor constructor
SendMail testMessage = new SendMail();
System.out.println("return from constructor");
System.out.println(testMessage + " Hello");
testMessage.Send(SMTPserver, SMTPport, Sender, Recipient, CcRecipient,
BccRecipient, Subject, Body, ErrorMessage, Attachments);
System.out.println("message sent");
Source SendMail---------------------------------------
package com.vdscomputing.carpinvest.ocbs.db.io;
import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendMail {
//default constructor with monitor message
public SendMail(){
System.out.println("Constructor entered");
// preparing the message and sending it
public static int Send(String SMTPServer,
String SMTPPort,
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);
props.put("mail.smtp.port", SMTPPort);
Session session = Session.getDefaultInstance(props, null);
try {
boolean ParseOption = false; //do not enforce RFC822
// create a message;
MimeMessage msg = new MimeMessage(session);
// extracts the senders and adds them to the message;
InternetAddress[] TheAddresses =
InternetAddress.parseHeader(Sender, ParseOption);
msg.addFrom(TheAddresses);
// extract the recipients and assign them to the message;
InternetAddress[] TheAddresses =
InternetAddress.parseHeader(Recipient, ParseOption);
msg.addRecipients(Message.RecipientType.TO,
TheAddresses);
// extract the Cc-recipients and assign them to the message;
if (null != CcRecipient) {
InternetAddress[] TheAddresses =
InternetAddress.parseHeader(CcRecipient, ParseOption);
msg.addRecipients(Message.RecipientType.CC,
TheAddresses);
// extract the Bcc-recipients and assign them to the message;
if (null != BccRecipient) {
InternetAddress[] TheAddresses =
InternetAddress.parseHeader(BccRecipient, ParseOption);
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 with monitor message
Transport.send(msg);
System.out.println("message on transport");
} catch (MessagingException MsgException) {
ErrorMessage[0] = MsgException.toString();
System.out.println(ErrorMessage[0]); // catch to console
Exception TheException = null;
if ((TheException = MsgException.getNextException()) !=
null)
ErrorMessage[0] = ErrorMessage[0] + "\n" +
TheException.toString();
ErrorStatus = 1;
return ErrorStatus;
}Hi,
I want to fax using java. presently I m using mail api to email & its working. Now I have to fax the attached pdf file with out using any third party or commercial software.
Any idea or suggestion would be very help full
regards
Prakash Sen -
Message subject,CC,header are displayed in the content part itself
This is the mail content i am getting::
>
Subject: Topic assigned in Discussion Forum
Cc: Some ID
Cc: Some ID
>
Mime-Version: 1.0
Content-Type: multipart/mixed;
boundary="----=_NextPartTM-000-2291bc8c-42c6-473e-bf3a-1907e8a05eed"
This is a multi-part message in MIME format.
------=_NextPartTM-000-2291bc8c-42c6-473e-bf3a-1907e8a05eed
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit
The following query has been assigned to sasasa
blah blah
------=_NextPartTM-000-2291bc8c-42c6-473e-bf3a-1907e8a05eed
Content-Type: text/plain;
name="InterScan_Disclaimer.txt"
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment;
filename="InterScan_Disclaimer.txt"
I am not setting the content type.
The content type is assumed by the mail server.
The code which i use is as follows::
public SendMail(Connection con,String incNo, String createdBy, String app, String priority,int upNo,String title,int flag)
String[] recipient_name = new String[10];
String[] recipient_mail_id = new String[10];
String sender_name = null;
String sender_id=null;
String msgText;
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy");
Calendar today = Calendar.getInstance();
String dt = sdf.format(today.getTime());
String dtinc=null;
System.out.println(createdBy+"creator");
try
Statement stmt = con.createStatement();
ResultSet rs1 = stmt.executeQuery(" select user_first_name + ' ' + user_last_name as user_name, e_mail as mail_id from Users where e_mail NOT IN ('','null') AND e_mail IS NOT NULL AND mailing_flag = 1 ");
int i=0;
while (rs1.next())
recipient_name[i] = rs1.getString("user_name");
recipient_mail_id[i] = rs1.getString("mail_id");
i++;
stmt = con.createStatement();
ResultSet rs2 = stmt.executeQuery(" select user_first_name + ' ' + user_last_name as user_name,e_mail as mail_id from Users " +
" where user_id = '" + createdBy + "'");
rs2.next();
sender_name = rs2.getString("user_name");
sender_id = rs2.getString("mail_id");
System.out.println(createdBy+sender_name);
System.out.println(createdBy+sender_id);
catch (Exception ex)
System.out.println(ex);
msgText = "A new update has been created for " + app;
msgText = msgText + "\nIncident # : " + incNo;
msgText = msgText + "\nUpdate # : " + upNo;
msgText = msgText + "\nTitle : " + title;
msgText = msgText + "\nCreated on : " + dt;
msgText = msgText + "\nCreated by : " + sender_name;
msgText = msgText + "\nPriority : " + priority;
String from = sender_name;
String host = "mail server IP";
boolean debug = Boolean.valueOf("true").booleanValue();
Properties props = new Properties();
props.put("mail.smtp.host", host);
if (debug) props.put("mail.debug", "true");
Session session = Session.getDefaultInstance(props, null);
session.setDebug(debug);
try
Message msg = new MimeMessage(session);
if(sender_id ==null || sender_id.equals("null")||sender_id.equals(""))
sender_id="Default";
System.out.println("From :::::::"+sender_id);
msg.setFrom(new InternetAddress(sender_id,from));
if(recipient_name[0]!=null)
InternetAddress toAddress = new InternetAddress(recipient_mail_id[0],recipient_name[0]);
msg.setRecipient(Message.RecipientType.TO, toAddress);
for(int i=1;!(recipient_name==null);i++)
if(recipient_name[i]!=null)
InternetAddress ccAddress = new InternetAddress(recipient_mail_id[i],recipient_name[i]);
msg.addRecipient(Message.RecipientType.CC, ccAddress);
msg.setSubject("Update Notification for Incident #: " + incNo);
msg.setSentDate(new java.util.Date());
msg.setContent(msgText, "text/html");
Transport.send(msg);
catch (UnsupportedEncodingException ex)
System.out.println("\n--UnsupportedEncodingException in msgsendsample.java");
catch (MessagingException mex)
System.out.println("\n--Exception handling in msgsendsample.java");
mex.printStackTrace();
System.out.println();
Exception ex = mex;
do {
if (ex instanceof SendFailedException) {
SendFailedException sfex = (SendFailedException)ex;
Address[] invalid = sfex.getInvalidAddresses();
if (invalid != null) {
System.out.println(" ** Invalid Addresses");
if (invalid != null) {
for (int i = 0; i < invalid.length; i++)
System.out.println(" " + invalid[i]);
Address[] validUnsent = sfex.getValidUnsentAddresses();
if (validUnsent != null) {
System.out.println(" ** ValidUnsent Addresses");
if (validUnsent != null) {
for (int i = 0; i < validUnsent.length; i++)
System.out.println(" "+validUnsent[i]);
Address[] validSent = sfex.getValidSentAddresses();
if (validSent != null) {
System.out.println(" ** ValidSent Addresses");
if (validSent != null) {
for (int i = 0; i < validSent.length; i++)
System.out.println(" "+validSent[i]);
System.out.println();
} while ((ex = ((MessagingException)ex).getNextException())
!= null);
return ;Good to see some other person also waiting for a reply!!
Well i know that the problem may arise when the message.settext() is used instead of message.setcontent()...
Also i have this problem rectified now and the change we did was
---some of the mail ids had capital letters in it.we changed all the letters to small letters
---change the settext to setcontent
I dont know whether these are the correct solutions
but may be this could help in getting the correct solution!!!!!!! -
How to attach a text file as an attachment to email message?
Hello Everybody,
I have a .csv file, in which details about emp-id, emp-name, e-expenses for Reimbursement and email address are stored.
My application reads this .csv file, and sends a mail to each employee with his id, salary details in text format. (by changing content type to "text/plain") The code is working fine. But,
My problem is:
The message is sent as message body to the end user.
The end user / the person who receives this mail will not be a technical person. So,
1) If he trys to take a print out of this e-mail, He get only half of it.(as no. of colums will be more than paper size).
2) I am finding alignment problem. IF employee name is too big, other columns will shift to right and data will not be exactly under column header. (it is going in zig zag way)
So, I thought sending text file with all the details as an attachment might do well.
But, I don't know how to attach a text file to email-message body.
code
try
{ String s1="";
File f1 = new File(the path);
FileInputStream fstream = new FileInputStream(f1); //new
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
int count=0;
while((s1=br.readLine())!=null )
count++;
//out.println("within while loop "+count);
StringTokenizer st = new StringTokenizer(s1,",");
if ((st.hasMoreTokens())&&(count>1))
String a=st.nextToken().trim();
String b=st.nextToken();
String c=st.nextToken();
String d=st.nextToken();
String e=st.nextToken();
String f=st.nextToken();
String g=st.nextToken();
String h=st.nextToken();
String i=st.nextToken();
String j=st.nextToken();
String k=st.nextToken();
String l=st.nextToken();
String m=st.nextToken();
String n=st.nextToken();
String o=st.nextToken();
String p=st.nextToken();
String q=st.nextToken();
String mail=st.nextToken();
String s=st.nextToken();
//out.println("b="+b+"c="+c+"d="+d+"e="+e+"f="+f+"mail="+mail);
%>
<%
String to =mail;
String from =request.getParameter("fromadd");
String subject ="Statement of Expenses";
String smtp ="mail.xxxxxxxxxx.com";
String message="";
message=message.concat("EMP ID");
message=message.concat(" ");
message=message.concat("Name");
message=message.concat(" ");
message=message.concat("Dept No.");
message=message.concat(" ");
message=message.concat("Acc No.");
message=message.concat(" ");
message=message.concat("*****************************************************************************************");
message=message.concat(a);
message=message.concat(" ");
message=message.concat(b);
message=message.concat(" ");
message=message.concat(c);
message=message.concat(" ");
message=message.concat(d);
Properties props = System.getProperties();
// Puts the SMTP server name to properties object
props.put("mail.smtp.host", smtp);
// Get the default Session using Properties Object
Session session1 = Session.getDefaultInstance(props, null);
// Create a New message
MimeMessage msg = new MimeMessage(session1);
// Set the From address
msg.setFrom(new InternetAddress(from));
// Setting the "To recipients" addresses
msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to, false));
/* // Setting the "cc recipients" addresses
msg.setRecipients(Message.RecipientType.CC,InternetAddress.parse(cc, false));
// Setting the "Bcc recipients" addresses
msg.setRecipients(Message.RecipientType.BCC,InternetAddress.parse(bcc, false)); */
// Sets the Subject
msg.setSubject(subject);
// set the meaasge in HTML format
msg.setContent(message,"text/plain");
// Set the Date: header
msg.setSentDate(new java.util.Date());
// Send the message
Transport.send(msg);
// Display Success message
result =result.concat("<tr><td>"+b+"</td>"+"<td>"+to+"</td></tr>");
}//end of if of hasmore element
}// end of while loop
out.println(result);
}catch(Exception e)
// If here, then error in sending Mail. Display Error message.
result="Unable to send your message";
out.println("e="+e);
Any help will be appreciated.
Thanks and regards.
Ashvini<html>
<p>
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText("Your Messages");
MimeBodyPart mbp2 = new MimeBodyPart();
FileDataSource fds = new FileDataSource("Your Attachments");
mbp2.setDataHandler(new DataHandler(fds));
mbp2.setFileName(fds.getName());
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
mp.addBodyPart(mbp2);
msg.setContent(mp);
msg.saveChanges();
msg.writeTo(System.out);
msg.setSubject(subject);
Transport.send(msg);
</p>
<B><U>See you can add above code in your program and see the magic</U></B>
Bye
regards--
Ashish
</html> -
Problem in sending messages using java mail api
Hi All,
I have a problem in sending messages via java mail api.
MimeMessage message = new MimeMessage(session);
String bodyContent = "ñSunJava";
message.setText (bodyContent,"utf-8");using the above code its not possible for me to send the attachment. if i am using the below code means special characters like ñ gets removed or changed into some other characters.
MimeBodyPart messagePart = new MimeBodyPart();
messagePart.setText(bodyText);
// Set the email attachment file
MimeBodyPart attachmentPart = new MimeBodyPart();
FileDataSource fileDataSource = new FileDataSource("C:/sunjava.txt") {
public String getContentType() {
return "application/octet-stream";
attachmentPart.setDataHandler(new DataHandler(fileDataSource));
attachmentPart.setFileName(filename);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messagePart);
multipart.addBodyPart(attachmentPart);
message.setContent(multipart);
Transport.send(message);is there any way to send the file attachment with the body message without using MultiPart java class.Taken pretty much straight out of the Javamail examples the following works for me (mail read using Thunderbird) // Define message
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
// Set the 'to' address
for (int i = 0; i < to.length; i++)
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// Set the 'cc' address
for (int i = 0; i < cc.length; i++)
message.addRecipient(Message.RecipientType.CC, new InternetAddress(cc[i]));
// Set the 'bcc' address
for (int i = 0; i < bcc.length; i++)
message.addRecipient(Message.RecipientType.BCC, new InternetAddress(bcc[i]));
message.setSubject("JavaMail With Attachment");
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText("Here's the file ñSunJava");
// Create a Multipart
Multipart multipart = new MimeMultipart();
// Add part one
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
for (int count = 0; count < 5; count++)
String filename = "hello" + count + ".txt";
String fileContent = " ñSunJava - Now is the time for all good men to come to the aid of the party " + count + " \n";
// Create another body part
BodyPart attachementBodyPart = new MimeBodyPart();
// Get the attachment
DataSource source = new StringDataSource(fileContent, filename);
// Set the data handler to this attachment
attachementBodyPart.setDataHandler(new DataHandler(source));
// Set the filename
attachementBodyPart.setFileName(filename);
// Add this part
multipart.addBodyPart(attachementBodyPart);
// Put parts in message
message.setContent(multipart);
// Send the message
Transport.send(message); -
How to send a message with javamail api
Hi, anybody can tell me how i do to send a message with javamail?
Thanks.
Daniele.[rossifumi80],
Here's a simple JavaMail application SendMessage.java that will connect a SMTP host and send a mail message out:
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class SendMessage {
public static void main (String args[]) throws Exception {
String host = args[0];
String from = args[1];
String to = args[2];
// Get system properties
Properties props = System.getProperties();
// Setup mail server
props.put("mail.smtp.host", host);
// Get session
Session session = Session.getDefaultInstance(props, null);
// Define message
MimeMessage message = new MimeMessage(session);
// Set the from address
message.setFrom(new InternetAddress(from));
// Set the to address
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set the subject
message.setSubject("Hello JavaMail");
// Set the content
message.setText("Welcome to JavaMail");
// Send message
Transport.send(message);
}HTH.
Allen Lai
Developer Technical Support
SUN Microsystems
http://www.sun.com/developers/support/ -
Sending email with message body contain data in table displayed in one
Hi,
I have one jsp page where I am dispalying the table data retrieved fron database.
Now i am trying to send this table as message body of the mail to the user.I am doing same stuff last from six days but unable to send such data.
Please help me Sir,as i am newbie here.
Here is an jsp page.
Document : evaluationeventtable
Created on : Jul 24, 2008, 6:52:37 PM
Author : user1
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page language ="java" %>
<%@ page import="java.sql.*, javax.sql.*, javax.naming.*,java.io.*,java.util.*" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>IGIDR</title>
<link rel="stylesheet" href="../styles/styles.css" type="text/css">
</head>
<body>
<table width="100%" cellspacing="0" cellpadding="0" border="0">
<tr>
<td><%@ include file="/includes/logohead.jsp" %></td>
</tr>
<tr><td><%@ include file="/toplinks.jsp"%></td></tr>
<tr>
<td width="100%" valign="top">
<table width="100%" cellspacing="0" cellpadding="0" border="1" borderColor=#000066>
<tr>
<td width="80%">
<% int QNO;
String message=null;
//String message1=null;
//String message2=null;
String noA,noB,noC,noD;
String ID=request.getParameter("id");
String EVENTID=request.getParameter("event");
Connection connection = null;
Statement st = null;
Statement st1 = null;
Statement st2 = null;
Statement st3 = null;
Statement st4 = null;
Statement st5 = null;
ResultSet rs= null;
ResultSet rs1= null;
ResultSet rs2= null;
ResultSet rs3= null;
ResultSet rs4= null;
ResultSet rs5= null;
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mynewdatabase","root", "root123");
st=con.createStatement();
try {
rs = st.executeQuery("SELECT * FROM Questionbank where Questionid='"+ID+"'");
%>
<table border="1" cellpadding="2" cellspacing="3" bgcolor="#E6E6FA" align="center"><tr><th>Questions</th><th>A</th><th>B</th><th>C</th><th>D</th></tr>
<% message="<table border=1 cellpadding=2 cellspacing=3 bgcolor=#E6E6FA align=center><tr><th>Questions</th><th>A</th><th>B</th><th>C</th><th>D</th></tr>";%>
<%
while ( rs.next() )
//String NO=rs.getString("Qserialno");
//session.setAttribute("no",NO);
//String NAME=rs.getString("questionname");
//session.setAttribute("name",NAME);
%>
<tr><td><%=rs.getString("Qserialno") + "." + rs.getString("questionname")%></td>
<%
message=message+"<tr><td>"+rs.getString("Qserialno") + "." + rs.getString("questionname")+"</td>";
st1=con.createStatement();
try
rs1=st1.executeQuery("select count(*) as total from final where questionid='"+ID+"'and Eventid='"+EVENTID+"'and Qserialno='"+rs.getString("Qserialno")+"'and Answer='A'");
rs1.next();
noA=rs1.getString("total");
session.setAttribute("NOA",noA);
rs1=st1.executeQuery("select count(*) as total from final where questionid='"+ID+"'and Eventid='"+EVENTID+"'and Qserialno='"+rs.getString("Qserialno")+"'and Answer='B'");
rs1.next();
noB=rs1.getString("total");
session.setAttribute("NOB",noB);
rs1=st1.executeQuery("select count(*) as total from final where questionid='"+ID+"'and Eventid='"+EVENTID+"'and Qserialno='"+rs.getString("Qserialno")+"'and Answer='C'");
rs1.next();
noC=rs1.getString("total");
session.setAttribute("NOC",noC);
rs1=st1.executeQuery("select count(*) as total from final where questionid='"+ID+"'and Eventid='"+EVENTID+"'and Qserialno='"+rs.getString("Qserialno")+"'and Answer='D'");
rs1.next();
noD=rs1.getString("total");
session.setAttribute("NOD",noD);
message=message+"<td>"+noA+"</td><td>"+noB+"</td><td>"+noC+"</td><td>"+noD+"</td></tr></table>";
%>
<td><%=noA%></td><td><%=noB%></td><td><%=noC%></td><td><%=noD%></td></tr>
<%
} finally
if (rs1 != null)
rs1.close();
rs1 = null;
} if (st1 != null)
st1.close();
st1 = null;
finally
if (rs != null)
rs.close();
rs = null;
if (st != null)
st.close();
st = null;
con.close();
%></table>
<table align="center" width="50%" cellspacing="0" cellpadding="0" border="1" borderColor=#D2691E>
<form name="sendmail" action="/student/servletmail" method="POST">
<tr class="CellColor">
<td>To</td>
<td class="CellColor" width="1%">
</td>
<td class="CellColor">
<input type="text" name="to" size="25" value="">
</td>
<td>From</td>
<td class="CellColor" width="1%">
</td>
<td class="CellColor">
<input type="text" name="from" size="25" value="">
</td>
</tr>
<input type="hidden" name="message" value="<%=message%>">
<tr class="CellColor">
<td class="CellColor" colspan="9" align="center">
<input type="submit" name="tn1" value="Send" >
</td>
</tr>
</form></table></td></tr></table>
</table>
</body></html> And here is an servlet where i am trying to send the mail
package com.student.igidr.test;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.mail.*;
import javax.mail.event.*;
import javax.mail.internet.*;
import javax.servlet.*;
import javax.servlet.http.*;
* @author user1
public class servletmail 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","webmail.igidr.ac.in"); // 'localhost' for testing
Session session1 = Session.getDefaultInstance(props,null);
String s1 = request.getParameter("to");
String s2 = request.getParameter("from");
//String s3 = request.getParameter("sub");
String s4 = request.getParameter("message");
// out.println(s4);
Message message =new MimeMessage(session1);
message.setFrom(new InternetAddress(s2));
message.setRecipients
(Message.RecipientType.TO,InternetAddress.parse(s1,false));
// message.setSubject(s3);
message.setText(s4);
message.setContent(s4,"text/html");
Transport.send(message);
out.println("mail has been sent");
catch(Exception ex)
System.out.println("ERROR....."+ex);
}I am using the message variable to send the message also as input variable in servlet.
Whether it is write Way to represent hole table body into message variable in jsp page.
Please help me.
Thanks and Regards
haresh
Edited by: HARSHAL_GURAV on Aug 13, 2008 11:15 PM
Edited by: HARSHAL_GURAV on Aug 13, 2008 11:56 PMHi bshannon ,
Thanks you very much for your reply.
I am trying to send html formated mail to the user.
The message body contains the table that is displayed in above jsp page as:
<table border="1" cellpadding="2" cellspacing="3" bgcolor="#E6E6FA" align="center"><tr><th>Questions</th><th>A</th><th>B</th><th>C</th><th>D</th></tr>
<tr><td><%=rs.getString("Qserialno") + "." + rs.getString("questionname")%></td>
<td><%=noA%></td><td><%=noB%></td><td><%=noC%></td><td><%=noD%></td></tr>In above code I am displaying the data from table i jsp page in table format. The data is related to analysis of particular event and i am trying to send this data as message body of the email.
As table displayed in html form can you assist me in how to send html data?
I am using variable message to store all this table data .
<% message="<table border=1 cellpadding=2 cellspacing=3 bgcolor=#E6E6FA align=center><tr><th>Questions</th><th>A</th><th>B</th><th>C</th><th>D</th></tr>";%>
message=message+"<tr><td>"+rs.getString("Qserialno") + "." + rs.getString("questionname")+"</td>";
message=message+"<td>"+noA+"</td><td>"+noB+"</td><td>"+noC+"</td><td>"+noD+"</td></tr></table>";i am sending this variable through form.At servlet I am retrieving it like:
String s1 = request.getParameter("to");
String s2 = request.getParameter("from");
//String s3 = request.getParameter("sub");
*String s4 = request.getParameter("message");*Will this possible ?
Please help meas i am troubling same with last from 7-8 days.
I had gone through Faqs but unable to collect required information.
Thanks and Regards
Haresh
Edited by: HARSHAL_GURAV on Aug 15, 2008 9:22 PM -
Using images in an HTML message
Dear All,
I want to embed 2 .gif files as part of the HTML message which is being sent from one client to another..My clients want me to give them the same effect as Outlook express utility: New Using->Select Stationery->Filename...so that the text can be typed on the image & then sent...i have hardcoded the structure of the message but the problem is that i am only able to send this message & view it only on my m/c & my e-mail id....if i send it to some other id the picture is not displayed how do i handle this
Thank You
Chaitraimport java.io.*;
import java.util.*;
import java.text.*;
import javax.mail.*;
import javax.servlet.*;
import javax.activation.*;
import javax.servlet.http.*;
import javax.mail.internet.*;
public class MailServlet
extends HttpServlet
protected void printForm(String form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException
PrintWriter writer = response.getWriter();
form = MessageFormat.format(form,
new Object[] { request.getServletPath() });
writer.print(form);
writer.flush();
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException
printForm(request.getParameter("SendMailForm"),request,response);
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException
try
if(request.getContentType().
startsWith("multipart/form-data"))
doUpload(request,response);
else
response.sendError(
HttpServletResponse.SC_NOT_FOUND);
catch(Exception e)
PrintWriter writer = response.getWriter();
writer.println("<HR><B>Oops!</B><PRE>");
e.printStackTrace(writer);
writer.println("</PRE>");
writer.flush();
protected void doSendMessage(HttpServletRequest request,
HttpServletResponse response,
Dictionary fields)
throws IOException, MessagingException
String host = "10.10.40.6";
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
Session session =
Session.getInstance(props, null);
Message msg =
new MimeMessage(
session); /*.getDefaultInstance(
System.getProperties(),null));*/
msg.setFrom(
new InternetAddress(
(String)fields.get("from")));
InternetAddress[] tos =
InternetAddress.parse((String)fields.get("to"));
msg.setRecipients(Message.RecipientType.TO,tos);
if(fields.get("cc") != null)
InternetAddress[] ccs =
InternetAddress.parse((String)fields.get("cc"));
msg.setRecipients(Message.RecipientType.CC,ccs);
msg.setSubject((String)fields.get("subject"));
msg.setSentDate(new Date());
String msgText ="<HTML><HEAD><TITLE id=ridTitle>Eximbirthday</TITLE>";
msgText+="<META http-equiv=Content-Type content=\"text/html; charset=windows-1252\"><BASE ";
msgText+="href=d:/Tomcat/webapps/Project/>";
msgText+="<META content=\"MSHTML 6.00.2600.0\" name=GENERATOR></HEAD>";
msgText+="<BODY id=ridBody bgColor=#e7e4d9 leftMargin=0 topMargin=0 marginheight=0";
msgText+="marginwidth=0>";
msgText+="<CENTER></CENTER>";
msgText+="<P></P>";
msgText+="<TABLE cellSpacing=0 cellPadding=0 width=\"100%\" border=0>";
msgText+="<TBODY>";
msgText+="<TR>";
msgText+="<TD vAlign=top align=left colSpan=2><IMG height=69 src=\"cid:hbday.gif\"";
msgText+="width=366 border=0></TD></TR>";
msgText+="<TR>";
msgText+="<TD vAlign=top align=left width=\"65%\" height=2>";
msgText+="<br><br><FONT color=#0000ff size=5>";
msgText+=(String)fields.get("body");
msgText+="</font></TD>";
msgText+="<TD vAlign=bottom align=right height=2><IMG height=394 src=\"cid:flowers.gif\"";
msgText+="width=296 border=0></TD></TR></TBODY></TABLE>";
msgText+="<DIV> </DIV></BODY></HTML>";
if(null == fields.get("attachment"))
// msg.setText((String)fields.get("body"));
msg.setContent(msgText,"text/html");
else
BodyPart body = new MimeBodyPart(),
attachment =(BodyPart)fields.get("attachment");
//body.setText((String)fields.get("body"));
// body.setHeader("Content-Disposition", "inline; filename=flowers.gif");
body.setContent(msgText, "text/html");
MimeMultipart multipart = new MimeMultipart("related");
multipart.addBodyPart(body);
multipart.addBodyPart(attachment);
body=new MimeBodyPart();
DataSource fds = new FileDataSource("D:/Tomcat/webapps/Project/hbday.gif");
body.setDataHandler(new DataHandler(fds));
body.setHeader("Content-ID","hbday.gif");
// Add part to multi-part
multipart.addBodyPart(body);
// Create 2nd part for the image
body = new MimeBodyPart();
// Fetch the image and associate to part
DataSource fds2 = new FileDataSource("D:/Tomcat/webapps/Project/flowers.gif");
body.setDataHandler(new DataHandler(fds2));
body.setHeader("Content-ID","flowers.gif");
// Add part to multi-part
multipart.addBodyPart(body);
msg.setContent(multipart);
Transport.send(msg);
response.sendRedirect(response.encodeRedirectURL("/Project/OkForm.jsp"));
public void doUpload(HttpServletRequest request,
HttpServletResponse response)
throws IOException, MessagingException
String boundary =
request.getHeader("Content-Type");
int pos = boundary.indexOf('=');
boundary = boundary.substring(pos + 1);
boundary = "--" + boundary;
ServletInputStream in =
request.getInputStream();
byte[] bytes = new byte[512];
int state = 0;
ByteArrayOutputStream buffer =
new ByteArrayOutputStream();
String name = null,
value = null,
filename = null,
contentType = null;
Dictionary fields = new Hashtable();
int i = in.readLine(bytes,0,512);
while(-1 != i)
String st = new String(bytes,0,i);
if(st.startsWith(boundary))
state = 0;
if(null != name)
if(value != null)
fields.put(name,
value.substring(0,
// -2 to remove CR/LF
value.length() - 2));
else if(buffer.size() > 2)
InternetHeaders headers =
new InternetHeaders();
MimeBodyPart bodyPart =
new MimeBodyPart();
DataSource ds =
new ByteArrayDataSource(
buffer.toByteArray(),
contentType,filename);
bodyPart.setDataHandler(
new DataHandler(ds));
bodyPart.setDisposition(
"attachment; filename=\"" +
filename + "\"");
bodyPart.setFileName(filename);
fields.put(name,bodyPart);
name = null;
value = null;
filename = null;
contentType = null;
buffer = new ByteArrayOutputStream();
else if(st.startsWith(
"Content-Disposition: form-data") &&
state == 0)
StringTokenizer tokenizer =
new StringTokenizer(st,";=\"");
while(tokenizer.hasMoreTokens())
String token = tokenizer.nextToken();
if(token.startsWith(" name"))
name = tokenizer.nextToken();
state = 2;
else if(token.startsWith(" filename"))
filename = tokenizer.nextToken();
StringTokenizer ftokenizer =
new StringTokenizer(filename,"\\/:");
filename = ftokenizer.nextToken();
while(ftokenizer.hasMoreTokens())
filename = ftokenizer.nextToken();
state = 1;
break;
else if(st.startsWith("Content-Type") &&
state == 1)
pos = st.indexOf(":");
// + 2 to remove the space
// - 2 to remove CR/LF
contentType =
st.substring(pos + 2,st.length() - 2);
else if(st.equals("\r\n") && state == 1)
state = 3;
else if(st.equals("\r\n") && state == 2)
state = 4;
else if(state == 4)
value = value == null ? st : value + st;
else if(state == 3)
buffer.write(bytes,0,i);
i = in.readLine(bytes,0,512);
doSendMessage(request,response,fields);
class ByteArrayDataSource
implements DataSource
byte[] bytes;
String contentType,
name;
ByteArrayDataSource(byte[] bytes,
String contentType,
String name)
this.bytes = bytes;
if(contentType == null)
this.contentType = "application/octet-stream";
else
this.contentType = contentType;
this.name = name;
public String getContentType()
return contentType;
public InputStream getInputStream()
// remove the final CR/LF
return new ByteArrayInputStream(
bytes,0,bytes.length - 2);
public String getName()
return name;
public OutputStream getOutputStream()
throws IOException
throw new FileNotFoundException();
This is the latest version ....which again doesnt work!!!!!
Thanx..
Chaitra -
Message.getRecipients() in java mail API
Hi~~
I got a problem about method Message.getRecipients().When I setthe parameter to Message.RecipientType.TO,it works fine and I can get thecorrect data.But when I set it to Message.RecipientType.CC, exception occurs:java.lang.NullPointerException.
Can you explain?Thanx!metalcure,
An answer awaits you at http://forum.java.sun.com/thread.jsp?forum=43&thread=158511 -
Email program not running. Messaging Exception coming,
I am making an program which will send the mail to a gmail account. On my laptop following are installed:
- Apache Tomcat
- Eclipse
But the servlet is not able to send the mail to gmail account. I am directly sending the mail to the gmail account. I dont have PostCard Server installed on my laptop.Following exception is coming:
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.*;
public class InServlet extends HttpServlet
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException
doGet(request,response);
public void doGet(HttpServletRequest request, HttpServletResponse response ) throws IOException
PrintWriter out=null;
out= response.getWriter();
response.setContentType("text/html");
new GetMail().getTheMessages();
out.println("The mail has been send successfully");
import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.SendFailedException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class GetMail {
static String msgText = "This is a message body.";
public void getTheMessages() {
String to = "[email protected]";
String from = "[email protected]";
String host = "localhost";
// create some properties and get the default Session
Properties props = new Properties();
props.put("MAIL.SMTP.HOST", "smtp.gmail.com");
props.put("MAIL.SMTP.PORT","25");
//props.put("MAIL.TRANSPORT.PROTOCOL","SMTP" );
Session session = Session.getInstance(props,null);
try {
// create a message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setSubject("JavaMail APIs Test");
msg.setSentDate(new Date());
msg.setText(msgText);
Transport.send(msg);
} catch (MessagingException mex) {
System.out.println("\n--Exception handling in GetMail.java");
mex.printStackTrace();
System.out.println();
Exception ex = mex;
do {
if (ex instanceof SendFailedException) {
SendFailedException sfex = (SendFailedException) ex;
Address[] invalid = sfex.getInvalidAddresses();
if (invalid != null) {
System.out.println(" ** Invalid Addresses");
if (invalid != null) {
for (int i = 0; i < invalid.length; i++)
System.out.println(" " + invalid);
Address[] validUnsent = sfex.getValidUnsentAddresses();
if (validUnsent != null) {
System.out.println(" ** ValidUnsent Addresses");
if (validUnsent != null) {
for (int i = 0; i < validUnsent.length; i++)
System.out.println(" " + validUnsent[i]);
Address[] validSent = sfex.getValidSentAddresses();
if (validSent != null) {
System.out.println(" ** ValidSent Addresses");
if (validSent != null) {
for (int i = 0; i < validSent.length; i++)
System.out.println(" " + validSent[i]);
System.out.println();
if (ex instanceof MessagingException)
ex = ((MessagingException) ex).getNextException();
else
ex = null;
} while (ex != null);
javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;
nested exception is:
java.net.ConnectException: Connection refused: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1282)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:370)
at javax.mail.Service.connect(Service.java:275)
at javax.mail.Service.connect(Service.java:156)
at javax.mail.Service.connect(Service.java:105)
at javax.mail.Transport.send0(Transport.java:168)
at javax.mail.Transport.send(Transport.java:98)
at GetMail.getTheMessages(GetMail.java:40)
at InDotComServlet.doGet(InDotComServlet.java:18)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454)
at java.lang.Thread.run(Thread.java:595)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:516)
at java.net.Socket.connect(Socket.java:466)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:232)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1250)
... 22 more
Edited by: carox on Dec 14, 2009 4:16 AMProperties are case sensitive. Furthermore, you need to look-up on google for the right properties (TLS and so on).
props.put("MAIL.SMTP.HOST", "smtp.gmail.com");
props.put("MAIL.SMTP.PORT","25"); -
How to send the same message to two SMTP servers
hi,
I need to send a message to two different SMTP servers.
I want to avoid the creation of new MimeMessage with a new Session.
the only way I've found was to keep a reference to the Properties instance that was used in the Session creation, and modify its "mail.smtp.host" property.
Is there another way? I must be missing something.
thanks,
oferhi,
I've already found the solution, so I'll post it here.
first I'll explain the purpose:
I needed to send the same message to a normal email server, and (for some of the recipients) to a special SMTP server that is on a different machine.
the following code demonstrate the solution.
thanks for your help.
ofer
----------code---------------
public class MultipleSendTest {
private final static Session server1 = createSession("somesmtp_server.com");
private final static Session _server2 = createSession("another_smtp_server.com");
public static void main(String args[]) throws Exception {
//create the message
MimeMessage m = new MimeMessage(_server1);
m.setText("body text");
m.addRecipients(Message.RecipientType.TO, "[email protected]");
m.setFrom(new InternetAddress("[email protected]"));
//send
send(m, _server1);
send(m, _server2);
private static void send(MimeMessage message, Session session) {
//for logging only
String host = session.getProperty("mail.smtp.host");
try {
Transport transport = session.getTransport("smtp");
transport.connect();
transport.sendMessage(message, message.getAllRecipients());
System.out.println("sent to " + host);
transport.close();
} catch (MessagingException e) {
System.out.println("failed to send to " + host);
private static Session createSession(String host) {
Properties properties = new Properties();
properties.setProperty("mail.smtp.host", host);
return Session.getInstance(properties);
----------code---------------
Maybe you are looking for
-
New MBP, is it ok?
Hi there, I recently sold my iMac 24" and my MacBook and bought a MBP. Im so happy with it, even though Ive been a Mac user for years, I am still really impressed with it, its the first 'Pro' Mac I've had and I love it! Im concerned that a couple thi
-
IRPT Security - Best Practice?
With xMII 11.5, we setup roles with navigation links to our irpt screens; however, that does not stop someone from typing the URL into a new browser window to pull up these screens. Is there a security document that details how to prevent this from
-
I'm reinstalling Windows 7. What information will I need to reinstall CS5?
Hello, I'm planning to wipe my hard drive and reinstall Windows 7. What will I need to reinstall CS5? Do I just need my serial number? How can I find that? Do I need to contact customer support if I can't find it? Thanks
-
I can't find the "Repeat" button in my Itunes.
I can't find the "Repeat" button in my Itunes, when I'm listenning to a music. I have reinstaled my Itunes, it didn't help.
-
Camera problem: photo bar changed place and automatically rotates horizontal
Hi everybody, I've searched the forum but I didn't find a similiar topic that describes my problem... After the update for Xperia 2.3.3 I'm having troubles with my camera. I CAN take photo's and video's but as soon as I've made a photo the miniature