在应用程序中发邮件 站点:爱心种子小博士 关键字:在应用程序中发邮件
|
在应用程序中发邮件 /*
* Created on 2004-4-26
*/
import javax.mail.*;
import java.util.*;
import javax.mail.internet.*;
public class SenderWithSMTPVer
{
String host="";
String user="";
String password="";
public void setHost(String host)
{
this.host=host;
}
public void setAccount(String user,String password)
{
this.user=user;
this.password=password;
}
public void send(String from,String to,String subject,String content)
{
Properties props = new Properties();
props.put("mail.smtp.host", host);//指定SMTP服务器
props.put("mail.smtp.auth", "true");//指定是否需要SMTP验证
try
{
Session mailSession = Session.getDefaultInstance(props);
mailSession.setDebug(true);//是否在控制台显示debug信息
Message message=new MimeMessage(mailSession);
message.setFrom(new InternetAddress(from));//发件人
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));//收件人
message.setSubject(subject);//邮件主题
message.setText(content);//邮件内容
message.saveChanges();
Transport transport = mailSession.getTransport("smtp");
transport.connect(host, user, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}catch(Exception e)
{
System.out.println(e);
}
}
public static void main(String args[])
{
SenderWithSMTPVer sm=new SenderWithSMTPVer();
sm.setHost("smtp.163.com");//指定要使用的邮件服务器
sm.setAccount("zz3zcwb","123456");//指定帐号和密码
/*
* @param String 发件人的地址
* @param String 收件人地址
* @param String 邮件标题
* @param String 邮件正文
*/
sm.send("[email protected]","[email protected]","标题","内容");
}
}
运行结果:
C:\java>java SenderWithSMTPVer
DEBUG: setDebug: JavaMail version 1.3.1
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.s
mtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.163.com", port 25
220 Coremail SMTP(Anti Spam) System (163com[20030606])
DEBUG SMTP: connected to host "smtp.163.com", port: 25
EHLO teacher
250-192.168.1.206
250-PIPELINING
250-AUTH LOGIN PLAIN NTLM
250-AUTH=LOGIN PLAIN NTLM
250 8BITMIME
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN NTLM"
DEBUG SMTP: Found extension "AUTH=LOGIN", arg "PLAIN NTLM"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Attempt to authenticate
AUTH LOGIN
334 VXNlcm5hbWU6
enozemN3Yg==
334 UGFzc3dvcmQ6
MTIzNDU2
235 Authentication successful
DEBUG SMTP: use8bit false
MAIL FROM:<[email protected]>
250 Ok
RCPT TO:<[email protected]>
250 Ok
DEBUG SMTP: Verified Addresses
DEBUG SMTP: [email protected]
DATA
354 End data with <CR><LF>.<CR><LF>
Message-ID: <13523740.1098517683121.JavaMail.cwb@teacher>
From: [email protected]
To: [email protected]
Subject: =?GBK?B?serM4g==?=
Mime-Version: 1.0
Content-Type: text/plain; charset=GBK
Content-Transfer-Encoding: base64
xNrI3Q==
.
250 Ok: queued as F8CjgrAMekGxqCQA.1
QUIT
C:\java> |
|
|
|