下面是我的程序,MailMessage类就是一个java bean,内容我就不贴出来了
出错的地方我在程序中标出了,高手们帮忙看看啊package mail;import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.StringTokenizer;public class SMTPClient { /**
* @param args
* @throws IOException
* @throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException, IOException {
// TODO Auto-generated method stub
MailMessage message=new MailMessage();
message.setFrom("[email protected]");
message.setTo("[email protected]");
String server="smtp.eyou.com";
message.setSubject("test");
message.setContent("test");
message.setDatafrom("wasingmon");
message.setDatato("wxm");
SMTPClient smtp=new SMTPClient(server,25);
boolean flag;
flag=smtp.sendMail(message,server);
if(flag){
System.out.println("邮件发送成功!");
}
else{
System.out.println("邮件发送失败!");
} }
private Socket socket;
public SMTPClient(String server,int port) throws UnknownHostException, IOException{
try{
socket=new Socket(server,25);
}catch(SocketException e){
System.out.println(e.getMessage());
}catch(Exception e){
e.printStackTrace();
}finally{
System.out.println("已经建立连接!");
} }
public void helo(String server,BufferedReader in,BufferedWriter out) throws IOException{
int result;
result=getResult(in);
if(result!=220){
throw new IOException("连接服务器失败");
}
result=sendServer("HELO "+server,in,out);
if(result!=250)
{
throw new IOException("注册邮件服务器失败!");
}
}
private int sendServer(String str,BufferedReader in,BufferedWriter out) throws IOException{
out.write(str);
out.newLine();
out.flush();
return getResult(in);
}
public int getResult(BufferedReader in){
String line="";
try{
line=in.readLine();
}catch(Exception e){
e.printStackTrace();
}
//从服务器返回消息中读出状态码,将其转换成整数返回
StringTokenizer st=new StringTokenizer(line," ");
return Integer.parseInt(st.nextToken());
}
public void mailfrom(String source,BufferedReader in,BufferedWriter out) throws IOException{
int result;
result=sendServer("MAIL FROM:<"+source+">",in,out);
if(result!=250){
throw new IOException("指定源地址错误");
}
}
/////////////
/////////////
/////////现在错误出在rcpt()这里,result是从服务器端返回的状态码,这里是设置收件人的地址,
///////////成功的话应该返回250,但是我跟踪了一下,返回的是553,后面还有一点提示消
////////息"553 host denies relay (eyou mta)"
////////这个什么意思?
//////////////
/////////////
public void rcpt(String touchman,BufferedReader in,BufferedWriter out) throws IOException{
int result;
result=sendServer("RCPT TO:<"+touchman+">",in,out);
if(result!=250){
throw new IOException("指定目的地址错误!");
}
}
public void data(String from,String to,String subject,String content,BufferedReader in,BufferedWriter out) throws IOException{
int result;
result=sendServer("DATA",in,out);
if(result!=354){
throw new IOException("不能发送数据");
}
out.write("From:"+from);
out.newLine();
out.write("To:"+to);
out.write("subject:"+subject);
out.newLine();
out.write(content);
out.newLine();
result=sendServer(".",in,out);
System.out.println(result);
if(result!=250)
{
throw new IOException("发送数据错误");
}
}
public void quit(BufferedReader in,BufferedWriter out) throws IOException{
int result;
result=sendServer("QUIT",in,out);
if(result!=221){
throw new IOException("未能正确退出");
}
}
public boolean sendMail(MailMessage message,String server){
try{
BufferedReader in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter out=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
helo(server,in,out);
mailfrom(message.getFrom(),in,out);
rcpt(message.getTo(),in,out);
data(message.getDatafrom(),message.getDatato(),message.getSubject(),message.getContent(),in,out);
System.out.println("dfa7");
quit(in,out);
System.out.println("dfa8");
}catch(Exception e){
e.printStackTrace();
return false;
}
return true;
}}
出错的地方我在程序中标出了,高手们帮忙看看啊package mail;import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.StringTokenizer;public class SMTPClient { /**
* @param args
* @throws IOException
* @throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException, IOException {
// TODO Auto-generated method stub
MailMessage message=new MailMessage();
message.setFrom("[email protected]");
message.setTo("[email protected]");
String server="smtp.eyou.com";
message.setSubject("test");
message.setContent("test");
message.setDatafrom("wasingmon");
message.setDatato("wxm");
SMTPClient smtp=new SMTPClient(server,25);
boolean flag;
flag=smtp.sendMail(message,server);
if(flag){
System.out.println("邮件发送成功!");
}
else{
System.out.println("邮件发送失败!");
} }
private Socket socket;
public SMTPClient(String server,int port) throws UnknownHostException, IOException{
try{
socket=new Socket(server,25);
}catch(SocketException e){
System.out.println(e.getMessage());
}catch(Exception e){
e.printStackTrace();
}finally{
System.out.println("已经建立连接!");
} }
public void helo(String server,BufferedReader in,BufferedWriter out) throws IOException{
int result;
result=getResult(in);
if(result!=220){
throw new IOException("连接服务器失败");
}
result=sendServer("HELO "+server,in,out);
if(result!=250)
{
throw new IOException("注册邮件服务器失败!");
}
}
private int sendServer(String str,BufferedReader in,BufferedWriter out) throws IOException{
out.write(str);
out.newLine();
out.flush();
return getResult(in);
}
public int getResult(BufferedReader in){
String line="";
try{
line=in.readLine();
}catch(Exception e){
e.printStackTrace();
}
//从服务器返回消息中读出状态码,将其转换成整数返回
StringTokenizer st=new StringTokenizer(line," ");
return Integer.parseInt(st.nextToken());
}
public void mailfrom(String source,BufferedReader in,BufferedWriter out) throws IOException{
int result;
result=sendServer("MAIL FROM:<"+source+">",in,out);
if(result!=250){
throw new IOException("指定源地址错误");
}
}
/////////////
/////////////
/////////现在错误出在rcpt()这里,result是从服务器端返回的状态码,这里是设置收件人的地址,
///////////成功的话应该返回250,但是我跟踪了一下,返回的是553,后面还有一点提示消
////////息"553 host denies relay (eyou mta)"
////////这个什么意思?
//////////////
/////////////
public void rcpt(String touchman,BufferedReader in,BufferedWriter out) throws IOException{
int result;
result=sendServer("RCPT TO:<"+touchman+">",in,out);
if(result!=250){
throw new IOException("指定目的地址错误!");
}
}
public void data(String from,String to,String subject,String content,BufferedReader in,BufferedWriter out) throws IOException{
int result;
result=sendServer("DATA",in,out);
if(result!=354){
throw new IOException("不能发送数据");
}
out.write("From:"+from);
out.newLine();
out.write("To:"+to);
out.write("subject:"+subject);
out.newLine();
out.write(content);
out.newLine();
result=sendServer(".",in,out);
System.out.println(result);
if(result!=250)
{
throw new IOException("发送数据错误");
}
}
public void quit(BufferedReader in,BufferedWriter out) throws IOException{
int result;
result=sendServer("QUIT",in,out);
if(result!=221){
throw new IOException("未能正确退出");
}
}
public boolean sendMail(MailMessage message,String server){
try{
BufferedReader in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter out=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
helo(server,in,out);
mailfrom(message.getFrom(),in,out);
rcpt(message.getTo(),in,out);
data(message.getDatafrom(),message.getDatato(),message.getSubject(),message.getContent(),in,out);
System.out.println("dfa7");
quit(in,out);
System.out.println("dfa8");
}catch(Exception e){
e.printStackTrace();
return false;
}
return true;
}}
解决方案 »
- NetBeans建立项目后生成三个java文件aboutbox app view……
- 请教java.util.Random类的用法,谢谢
- [闭月羞花猫]关于LDAP中各个字段的问题
- 反编译class,然后查看
- 请问new Object() 有什么用处
- www.apache.org怎么了?
- bool值:10 > 5 && 1 > 0 || 3 > 5 || 20 == 8
- 如何用java实现Excel表格(具有合并拆分计算等功能)?
- 关于获取在jsp上获取客户端时间的问题
- 谈谈大家对io的认识
- 基于SMTP的邮件发送程序,不知道那里出错了!
- Java 代码的性能咨询与探讨(一段代码的性能改进问题)。。。。。。。
try {
Properties props = new Properties();
Session sendMailSession;
Store store;
Transport transport;
props.put("mail.smtp.host", getSMTPServer());
props.put( "mail.smtp.auth", "true" );
com.neower.sms.web.Auth auth = new com.neower.sms.web.Auth(getUser(),getPassword());
sendMailSession = Session.getInstance(props, auth);
transport = sendMailSession.getTransport("smtp");
transport.connect(getSMTPServer(), 25, getUser(), getPassword()); MimeMessage newMessage = new MimeMessage(sendMailSession);
newMessage.setFrom(new InternetAddress(getFrom()));
newMessage.setSubject(getSubject());
newMessage.setSentDate(new Date());
/*
StringTokenizer tokenTO = new StringTokenizer(to, ",");
InternetAddress[] addrArrTO = new InternetAddress[tokenTO.countTokens()];
int i = 0;
while(tokenTO.hasMoreTokens()) {
addrArrTO[i] = new InternetAddress(tokenTO.nextToken().toString());
i++;
}
*/
//newMessage.setRecipients(Message.RecipientType.TO, addrArrTO);
newMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
//newMessage.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
//newMessage.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc)); MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(getContent());
//System.out.println(getContent());
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
if(hasFile == 1) {
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(fileAttachment);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileAttachment); }
multipart.addBodyPart(messageBodyPart);
newMessage.setContent(multipart);
transport.send(newMessage);
}
catch(Exception e) {
System.out.println(e);
}
}
private String user,pwd; public Auth( String user, String pwd ) {
this.user = user;
this.pwd = pwd;
} protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new javax.mail.PasswordAuthentication( this.user, this.pwd );
}
}
但是在SMTP下用什么命令给主机发送用户名和密码?
还有我也用JavaMail写了一个,验证也加上了,但是还是有错误,好像是连不上主机
帮忙看看程序错误在哪儿?
package mail;import java.util.*;import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.*;
import javax.mail.*;public class JavaMail {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Properties props=new Properties();
props.put("mail.smtp.host","smtp.eyou.com");
props.put("mail.smtp.auth","true");
PopupAuthenticator auth=new PopupAuthenticator("wasingmon", "123456");
try{
Session session=Session.getInstance(props,auth);
MimeMessage message=new MimeMessage(session);
Address addressTo=new InternetAddress("[email protected]","wxm");
Address addressFrom=new InternetAddress("[email protected]","wxm");
Address addressCopy=new InternetAddress("[email protected]","wxm");
message.setContent("hello","text/plain");
message.setSubject("test");
message.setFrom(addressFrom);
message.addRecipient(Message.RecipientType.TO,addressTo);
message.addRecipient(Message.RecipientType.CC,addressCopy);
message.saveChanges();
Transport transport=session.getTransport("smtp");
///////////////////////////
///////////////下面的地方有异常:
///////////////发送失败!
//////////////javax.mail.AuthenticationFailedException
///////////// at javax.mail.Service.connect(Service.java:267)
//////////// at mail.JavaMail.main(JavaMail.java:40)
///////////////////////////////////////
transport.connect("smtp.eyou.com",25,"wasingmon","123456");
Transport.send(message);
transport.close();
System.out.println("Succ!");
}catch(Exception e){
e.printStackTrace();
System.out.println("发送失败!");
}
}
}class PopupAuthenticator extends Authenticator{
private String username,password;
public PopupAuthenticator(String username,String password){
this.password=password;
this.username=username;
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(this.username,this.password);
}
}PS:原程序中的用户名和密码都对着呢,我现在用的邮箱。
如下:
import java.io.*;/**
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2005</p>
* <p>Company: </p>
* @author not attributable
* @version 1.0
*/public class SendMail {
//private String to = null;//接收邮件的地址
//private String from = null;//发送邮件地址
private String accpetAddr = ""; //接收地址
private String sendAddr = ""; //发送地址
private String host = ""; //邮件服务器地址
private String pUserName = ""; //发送邮箱用户名
private String pPwd = ""; //发送邮箱密码 private String content = ""; //邮件内容
private String subject = ""; //邮件标题
private java.util.Calendar dat = java.util.Calendar.getInstance(); private boolean auth = true; //连接SMTP邮件服务器是否需要用户名密码
private boolean debug = true; //在服务起显示发送邮件信息 private java.util.Properties prop = System.getProperties(); //获得邮件服务器属性 /*
java.util.Properties prop = java.util.Properties();
javax.mail.Session session = javax.mail.Session.getDefaultInstance();
private javax.mail.Message msg = new javax.mail.internet.MimeMessage();
*/ /**
* 获得发送邮件的必须内容
* @param acceptMailAddress 接受邮件的邮箱(如:XXX◎163.com)
* @param sendMailAddress 发送邮件的邮箱(如:YYY◎163.com)
* @param mailServerHost 发送邮件服务器的地址(如:mail.163.com)
* @param sendMailUsername 发送邮件的邮箱的用户名(如:XXX◎163.com中的 XXX 不带域名即不带◎后面的)
* @param sendMailPwd 发送邮件的邮箱的密码
* @param mailContent 发送邮件的内容
* @param mailSubject 发送邮件的主题
*/
public SendMail(String acceptMailAddress, String sendMailAddress,
String mailServerHost, String sendMailUsername,
String sendMailPwd, String mailContent, String mailSubject) {
accpetAddr = acceptMailAddress;
sendAddr = sendMailAddress;
host = mailServerHost;
pUserName = sendMailUsername;
pPwd = sendMailPwd;
content = mailContent;
try {
subject = new String(mailSubject.getBytes(), "ISO-8859-1");
}
catch (Exception e) {
System.out.print("发生不可预知的错误,请重新启动该程序!!-.-!!");
return;
} } public boolean isSucc() {
return sendmail();
} private boolean sendmail() {
//设置邮件服务器SMTP名字
prop.put("mail.stmp.host", host);
//设置邮件服务器是否需要用户验证的变量
prop.put("mail.stmp.auth", String.valueOf(auth));
//设置是否显示发送邮件时信息的变量
if (debug) {
prop.put("mail.debug", String.valueOf(debug));
}
//创建发送邮件进程
javax.mail.Session mail_session = javax.mail.Session.getInstance(prop, null);
//定义是否显示发送邮件时的信息
mail_session.setDebug(debug); try {
//创建邮件发送包
javax.mail.Message msg = new javax.mail.internet.MimeMessage(mail_session);
//设置邮件发送包的发送地址
msg.setFrom( (new javax.mail.internet.InternetAddress(sendAddr)));
//设置邮件接收地址
javax.mail.internet.InternetAddress[] addrs = {
new javax.mail.internet.InternetAddress(accpetAddr)};
//设置邮件发送包的接受地址
msg.setRecipients(javax.mail.Message.RecipientType.TO, addrs);
//设置邮件主题
msg.setSubject(subject);
//设置邮件发送时间
msg.setSentDate(new java.util.Date());
//设置邮件的内容
msg.setText(content);
//保存msg
msg.saveChanges();
//连接SMTP服务器时需要输入的用户名和密码的执行代码
javax.mail.Transport transport = mail_session.getTransport("smtp");
if (auth) { //使用用户名和密码连接SMTP服务器
transport.connect(host, pUserName, pPwd);
//发送邮件
transport.sendMessage(msg, msg.getAllRecipients());
transport.close(); }
else {
//连接时不需要输入用户名和密码的操作
transport.send(msg);
}
return true;
}
catch (Exception e) {
System.out.println(e.getMessage());
return false;
}
} public static void main(String[] args) {
SendMail sendMail1 = new SendMail("接收邮件邮箱", "发送邮件邮箱",
"发送邮件服务器的地址", "用户名", "密码",
"邮件内容");
sendMail1.isSucc();
}}
250-wxm Hello [127.0.0.1]
250-SIZE 2097152
250-PIPELINING
250-DSN
250-ENHANCEDSTATUSCODES
250-8bitmime
250-BINARYMIME
250-CHUNKING
250-VRFY
250 OK
DEBUG SMTP: Found extension "SIZE", arg "2097152"
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "DSN", arg ""
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "8bitmime", arg ""
DEBUG SMTP: Found extension "BINARYMIME", arg ""
DEBUG SMTP: Found extension "CHUNKING", arg ""
DEBUG SMTP: Found extension "VRFY", arg ""
DEBUG SMTP: Found extension "OK", arg ""
DEBUG SMTP: use8bit false
MAIL FROM:<[email protected]>
250 2.1.0 [email protected] OK
RCPT TO:<[email protected]>
550 5.7.1 Unable to relay for [email protected]
DEBUG SMTP: Invalid Addresses
DEBUG SMTP: [email protected]
DEBUG SMTP: Sending failed because of invalid destination addresses
RSET
250 2.0.0 Resetting
javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
class com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to relay for [email protected] at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1141)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:536)
at javax.mail.Transport.send0(Transport.java:151)
at javax.mail.Transport.send(Transport.java:80)
at mail.SendMail.sendmail(SendMail.java:114)
at mail.SendMail.isSucc(SendMail.java:69)
at mail.SendMail.main(SendMail.java:134)
QUIT
Invalid Addresses;
nested exception is:
class com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to relay for [email protected]
楼上的,还是不行啊
仍然是这个错误,加上验证也不行
高手帮帮忙啊
//不用javaMail发送邮件
import java.net.*;
import java.io.*;
import java.util.*;public class SmtpTalk {
BufferedReader is;
PrintStream os;
private boolean debug=true;
private String host;
sun.misc.BASE64Encoder enc;
private String user;
private String psw;
public static void main(String[] argv){
if(argv.length!=2){
System.out.println("Usage:java SmtpTalk host user");
System.exit(1);
}
try{
SmtpTalk st=new SmtpTalk(argv[0]);
System.out.println("Smtp Talker ready");
st.converse("[email protected]",argv[1],"Test message",
"helo there");
}catch(Exception ig){
System.err.println(ig.getMessage());
System.exit(1);
}
}
SmtpTalk(String Server){
host=Server;
enc = new sun.misc.BASE64Encoder();
user=new String("madass");
psw=new String ("xinxin");
try{
Socket s=new Socket(host,25);
is=new BufferedReader(new InputStreamReader(s.getInputStream()));
os=new PrintStream(s.getOutputStream());
}
catch(NoRouteToHostException e){
die(/*EX_TEMPFAIL*/1,"No route to host "+host);
}
catch(ConnectException e){
die(/*EX_TEMPFAIL*/1,"Connection Refused by"+host);
}
catch(UnknownHostException e){
die(/*EX_NOHOST*/2,"Unknown host "+host);
}
catch(IOException e){
die(/*EX_IOERR*/3,"I/O error setting up socket stream\n"+e);
}
}
protected void send_cmd (String cmd,String oprnd){
send_cmd(cmd+" "+oprnd);
}
protected void send_cmd(String cmd){
if(debug)
System.out.println(">>>"+cmd);
os.print(cmd+"\r\n");
}
public void send_text(String text){
os.print(text+"\r\n");
}
protected boolean expect_reply(String rspNum) /*throw SMTPException*/{
String s=null;
try{
s=is.readLine();
}catch(IOException e){
die(/*EX_IOERR*/3,"I/o error reading from host"+host+" "+e);
}
if(debug) System.out.println("<<<"+s);
return s.startsWith(rspNum+" ");
}
protected void die(int ret,String msg)/* throw SMTPException*/{
//throw new SMTPException (ret,msg);
}
public void converse(String sender,String recipients,String subject,String body) /*throw SMTPException*/{
if(!expect_reply("220")) die(/*EX_PROTOCOL*/4,"did not get SMTP greeting");
send_cmd("HELO","[email protected]");
if(!expect_reply("250")) die(/*EX_PROTOCOL*/4,"did not get ack our HELO");
send_cmd("RSET");
if(!expect_reply("250")) die (/*EX_PROTOCOL*/4,"not reset");
send_cmd("AUTH LOGIN");
if(!expect_reply("334")) die (/*EX_PROTOCOL*/4,"not reset");
send_cmd(enc.encode(user.getBytes()));
if(!expect_reply("334")) die (/*EX_PROTOCOL*/4,"not reset");
send_cmd(enc.encode(psw.getBytes()));
if(!expect_reply("334")) die (/*EX_PROTOCOL*/4,"not reset");
send_cmd("MAIL","From:<"+sender+">");
if(!expect_reply("250")) die (/*EX_PROTOCOL*/4,"did not ack our MAIL command");
//StringTokenizer st=new StringTokenizer(recipients);
//while(st.hasMoreTokens()){
//String r=st.nextToken();
send_cmd("RCPT","To:<"+recipients+">");
if(!expect_reply("250"))
die(/*EX_PROTOCOL*/4,"did not ack RECP");
//}
send_cmd("DATA");
if(!expect_reply("354")) die(/*EX_PROTOCOL*/4,"did not want our data");
send_text("From: "+sender);
send_text("To: "+recipients);
send_text("Subject: "+subject);
send_text("");
send_text(body+"\r");
send_cmd(".");
if(!expect_reply("250")) die(/*EX_PROTOCOL*/4,"mail not accepted");
send_cmd("QUIT");
if(!expect_reply("221")) die(/*EX_PROTOCOL*/4,"Other end not closing down");
}
}
send_cmd("AUTH LOGIN");
if(!expect_reply("334")) die (/*EX_PROTOCOL*/4,"not reset");
send_cmd(enc.encode(user.getBytes()));
if(!expect_reply("334")) die (/*EX_PROTOCOL*/4,"not reset");
send_cmd(enc.encode(psw.getBytes()));
if(!expect_reply("334")) die (/*EX_PROTOCOL*/4,"not reset");
-----------------------------------------------至于使用javamail发送的细节 请搜索一下该论坛 很多的,