public SendMail(String smtp) { setSmtpHost(smtp); createMimeMessage(); } /** * Just do it as this */ public static void main(String[] args) { String mailbody = "测试邮件"; SendMail themail = new SendMail("192.168.1.1"); themail.setNeedAuth(true); if (themail.setSubject("Mail标题") == false) { return; } if (themail.setBody(mailbody) == false) { return; } if (themail.setTo("送信人Mail") == false) { return; } if (themail.setFrom("受信人Mail") == false) { return; } themail.setCopyTo("CC人Mail");
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Properties;import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;public class SendMail {
private MimeMessage mimeMsg; //MIME邮件対象
private Session session; //Session
private Properties props; //System属性
// private boolean needAuth = false; //smtp認証Flag
private String username = ""; //用户名
private String password = ""; //密码
private Multipart mp; //邮件詳細内容
public SendMail(String smtp) {
setSmtpHost(smtp);
createMimeMessage();
} /**
* Just do it as this
*/
public static void main(String[] args) {
String mailbody = "测试邮件";
SendMail themail = new SendMail("192.168.1.1");
themail.setNeedAuth(true);
if (themail.setSubject("Mail标题") == false) {
return;
}
if (themail.setBody(mailbody) == false) {
return;
}
if (themail.setTo("送信人Mail") == false) {
return;
}
if (themail.setFrom("受信人Mail") == false) {
return;
}
themail.setCopyTo("CC人Mail");
//添付ファイルの絶対パス
String filePath = "附件.doc";
if (themail.addFileAffix(filePath) == false) {
return; //添付ファイルの絶対パス
}
themail.setNamePass("用户名","密码"); //ユーザ名とパスワード
if(themail.sendout() == false) {
return;
}
}
/**
* @param hostName String
*/
public void setSmtpHost(String hostName) {
System.out.println("系统属性:mail.smtp.host = "+hostName);
if(props == null) {
props = System.getProperties(); //系统属性对象を取得する。
}
props.put("mail.smtp.host", hostName); //SMTP hostを設定する。
}
/**
* @return boolean
*/
public boolean createMimeMessage() {
try {
session = Session.getDefaultInstance(props, null); //セッションの取得
} catch(Exception e) {
System.err.println("セッションを取得するとき、エラー発生しました。"+e);
return false;
}
System.out.println("MIMEメール対象の生成");
try{
mimeMsg = new MimeMessage(session); //MIMEメール対象
mp = new MimeMultipart(); //mp メール詳細対象
//Multipart is a container that holds multiple body parts.
return true;
} catch(Exception e) {
System.err.println("MIMEメール対象の生成失敗。"+e);
return false;
}
}
/**
* @param need boolean
*/
public void setNeedAuth(boolean need) {
System.out.println("smtp認証の設定:mail.smtp.auth = " + need);
if (props == null) {
props = System.getProperties();
}
if (need) {
props.put("mail.smtp.auth", "true");
} else {
props.put("mail.smtp.auth", "false");
}
}
/**
* @param name String
* @param pass String
*/
public void setNamePass(String name,String pass) {
System.out.println("ユーザ名とパスワードの設定");
username = name;
password = pass;
}
/**
* @param mailSubject String
* @return boolean
*/
public boolean setSubject(String mailSubject) {
System.out.println("メールタイトルの設定!");
try {
mimeMsg.setSubject(mailSubject);
return true;
} catch(Exception e) {
System.err.println("メールタイトルの設定失敗。");
return false;
}
} /**
* @param mailBody String
*/
public boolean setBody(String mailBody) {
try {
System.out.println("メール内容のフォントを設定する");
BodyPart bp = new MimeBodyPart();
bp.setContent("" + mailBody, "text/html;charset=Shift-JIS");
mp.addBodyPart(bp);
return true;
} catch(Exception e) {
System.err.println("メール内容のフォントを設定する時、エラーは発生しました。"+e);
return false;
}
} /**
* @param name String
* @param pass String
*/
public boolean addFileAffix(String filename) {
System.out.println("メールの添付ファイルを追加すること:" + filename);
try {
BodyPart bp = new MimeBodyPart();
FileDataSource fileds = new FileDataSource(filename);
bp.setDataHandler(new DataHandler(fileds));
bp.setFileName(fileds.getName());
mp.addBodyPart(bp);
return true;
} catch(Exception e) {
System.err.println("添付ファイル:" + filename + "エラーが発生しました。" + e);
return false;
}
} /**
* @param name String
* @param pass String
*/
public boolean setFrom(String from) {
System.out.println("送信人の設定");
try {
mimeMsg.setFrom(new InternetAddress(from)); //差出人の設定
return true;
} catch(Exception e) {
return false;
}
}
/**
* @param name String
* @param pass String
*/
public boolean setTo(String to) {
System.out.println("宛先の設定");
if (to == null) {
return false;
}
try {
mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
return true;
} catch(Exception e) {
return false;
}
} /**
* @param name String
* @param pass String
*/
public boolean setCopyTo(String copyto) {
System.out.println("send file to");
if (copyto == null) {
return false;
}
try {
mimeMsg.setRecipients(Message.RecipientType.CC,(Address[])InternetAddress.parse(copyto));
return true;
} catch(Exception e) {
return false;
}
} /**
* @param name String
* @param pass String
*/
public boolean sendout() {
try {
mimeMsg.setContent(mp);
mimeMsg.saveChanges();
System.out.println("メールを送付中…");
Session mailSession = Session.getInstance(props, null);
Transport transport = mailSession.getTransport("smtp"); //
transport.connect((String)props.get("mail.smtp.host"), username, password);
transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.TO));
//transport.send(mimeMsg);
System.out.println("メール送付成功。");
transport.close();
return true;
} catch(Exception e) {
System.err.println("メール送付失敗" + e);
return false;
}
}}
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.telecom.struts.action;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.telecom.struts.form.NsendEmailForm;
import java.util.*;//用来发送邮件的包
import javax.mail.*;//用来发送邮件的包
import javax.mail.internet.*;//用来发送邮件的包
/**
* MyEclipse Struts
* Creation date: 07-04-2009
*
* XDoclet definition:
* @struts.action path="/nsendEmail" name="nsendEmailForm" input="/InsideNet/html/web/tab/sendEmail.jsp" scope="request" validate="true"
*/
public class NsendEmailAction extends Action {
/*
* Generated Methods
*/
//定义一个过滤器类 public String codeToString(String str)
{
String s=str;
try
{ byte tempB[]=s.getBytes("ISO-8895-1");
s=new String(tempB);
return s;
}
catch(Exception e)
{
return s;
}
}
/**
* Method execute
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
NsendEmailForm nsendEmailForm = (NsendEmailForm) form;// TODO Auto-generated method stub
String context=codeToString(nsendEmailForm.getEmailContext());
String title=codeToString(nsendEmailForm.getEmailTitle());
String people=codeToString(nsendEmailForm.getReceivePeople()); try
{
Properties props=new Properties();
props.put("mail.smtp.host","smtp.sina.com");
props.put("mail.smtp.auth","true");
Session s=Session.getInstance(props);
s.setDebug(true);
//由邮件会话新建一个消息对象
MimeMessage message=new MimeMessage(s);
//设置邮件
InternetAddress form1=new InternetAddress("[email protected]");
message.setFrom(form1);//设置发件人 InternetAddress to=new InternetAddress(people);
message.setRecipient(Message.RecipientType.TO,to);//设置收件人 message.setSubject(title);//设置邮件的主题
message.setText(context);//设置邮件的内容
message.setSentDate(new Date());//设置邮件发送时间
//发送邮件
message.saveChanges();
Transport transport=s.getTransport("smtp");
transport.connect("smtp.sina.com","weiliu_china","liuwei");
transport.sendMessage(message,message.getAllRecipients());
transport.close();
return mapping.findForward("success");
}
catch(Exception e)
{
return mapping.findForward("fair");
}
}
}
要符合esmtp协议 而不是smtp协议
不过新注册的163帐号屏蔽了某些功能, 老的163帐号是没问题的 当然这个是传说了,没实验过
这段代码好像不行吧,我试了一下,总是报错com.sun.mail.smtp.SMTPSendFailedException:553 authentication is required,smtp3,DdGowKCLA2FPlqBLwIgZDA--.45545S2 1268815439
public static void main(String[] args) throws AddressException,
MessagingException {
String to = "****@163.com";
String from = "***@163.com";
Properties props = new Properties();
Session sendMailSession;
Transport transport;
props.put("mail.smtp.host", "smtp.163.com"); // 这里填写你发信者的SMTP主机,如:smtp.sohu.com
// props.put("mail.smtp.user", usr);
// props.put("mail.smtp.password", pwd);
props.put("mail.smtp.auth", "true");
sendMailSession = Session.getInstance(props, new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("***@163.com", "***");
}// 这里填写你发信者的邮箱地址和密码
});// 如果你的邮箱是SMTP验证的,就得这么写。否则会报错。Session.getInstance(props)这个方法是针对SMTP不要求验证的,我的邮箱要验证,所以得这么写。
Message newMessage = new MimeMessage(sendMailSession);
newMessage.setFrom(new InternetAddress(from));
newMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(
to));
newMessage.setSubject("Stamp");
newMessage.setSentDate(new Date());
newMessage.setText("Stamp");
transport = sendMailSession.getTransport("smtp");
Transport.send(newMessage);
}
}