有一些内容介绍(文字和图片)和几个附件,要发送到指定的邮箱里。怎么做?
我对Mail的发信和收信没有什么了解,只是会用。
我对Mail的发信和收信没有什么了解,只是会用。
解决方案 »
- 服务器怎么把客户端的聊天内容push到各个在线的其他客户端同步显示?
- JFrame如何实现模态化
- java如何编写C/S模式下的网络数据库程序
- 字符串中添加空格的小问题
- 调试不出来,错在哪里
- 网络编程问题:怎么在一个客户端接受多个服务器端传来的信息?
- 怎么构造一个dateformat,是24小时制的
- 一个跟随鼠标的问题
- 用jbuilder的例子运行时,却提示:Unlicensed copy of JDataStore. Use the License Manager in the JDataStore Explorer to register JDataStore.
- java语言 有大神么
- 拜托大家帮帮忙看看?怎么老是报异常?
- JSP中怎样获取地址栏中的信息?
http://www.cn-java.com/target/news.php?news_id=1928
http://www.cn-java.com/target/news.php?news_id=1534
http://www.cn-java.com/target/news.php?news_id=1001
http://www.cn-java.com/target/news.php?news_id=944
http://www.cn-java.com/target/news.php?news_id=2633
成功了
但是 public SendMail() {
setSmtpHost(getConfig.mailHost);//如果没有指定?件服?器,就从getConfig?中?取
createMimeMessage();
}
中的getConfig.mailHost怎么得到?下面是红线,编译不过去。
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import javax.swing.*; public class Sender extends JFrame{
//javamail Session对象
protected Session session; //java message对象
protected MimeMessage mesg;
protected Multipart mp;
//GUI
public JLabel smtpLab=new JLabel("SMTP服务器",SwingConstants.CENTER);
public JTextField smtpTF=new JTextField("smtp.163.net",20);;
public JLabel userLab=new JLabel("发送者邮箱",SwingConstants.CENTER);
public JTextField userName=new JTextField("[email protected]",20);;
public JLabel pwLab=new JLabel("登陆密码",SwingConstants.CENTER);
public JPasswordField passWord=new JPasswordField(20);;
public JLabel recpLab=new JLabel("收信者邮箱",SwingConstants.CENTER);
public JTextField recp=new JTextField("[email protected]",20);
public JLabel subjectLab=new JLabel("主题",SwingConstants.CENTER);
public JTextField subject=new JTextField("HelloMail",20);
public JButton browser=new JButton("浏览附件");
public JTextArea msg=new JTextArea(12,10);
public JButton sendBT=new JButton("发送邮件");
public JButton clearBT=new JButton("清除文本");
//附件
Vector files=new Vector();
public Sender(String str){
super(str);
Container cp=getContentPane();
cp.setLayout(new BorderLayout());
//north
JPanel paneNorth=new JPanel();
paneNorth.setLayout(new GridLayout(6,2));
paneNorth.setBackground(Color.cyan);
paneNorth.add(smtpLab);
paneNorth.add(smtpTF);
paneNorth.add(userLab);
paneNorth.add(userName);
paneNorth.add(pwLab);
paneNorth.add(passWord);
paneNorth.add(recpLab);
paneNorth.add(recp);
paneNorth.add(subjectLab);
paneNorth.add(subject);
paneNorth.add(new JLabel("选择附件",SwingConstants.CENTER));
paneNorth.add(browser);
browser.setForeground(Color.BLUE);
browser.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JFileChooser chooser=new JFileChooser();
int returnVal;
returnVal=chooser.showOpenDialog(Sender.this);
if(returnVal==JFileChooser.APPROVE_OPTION){}
files.addElement(chooser.getSelectedFile().getPath());
System.out.println(chooser.getSelectedFile().getPath());
}
});
cp.add(paneNorth,BorderLayout.NORTH);
//center
JScrollPane msgScroll=new JScrollPane(msg);
cp.add(msgScroll,BorderLayout.CENTER);
//south
JPanel panelSouth=new JPanel();
panelSouth.setBackground(Color.cyan);
panelSouth.add(sendBT);
sendBT.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
doSend();
}
});
panelSouth.add(clearBT);
clearBT.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
msg.setText("");
}
});
cp.add(panelSouth,BorderLayout.SOUTH);
setSize(400,300);
pack();
}
//添加附件
public void affix() {
String fileAffix;
Enumeration enum=files.elements();
while(enum.hasMoreElements()){
try{
MimeBodyPart mbp=new MimeBodyPart();
fileAffix=enum.nextElement().toString();
FileDataSource fs=new FileDataSource(fileAffix);
mbp.setDataHandler(new DataHandler(fs));
mbp.setFileName(MimeUtility.encodeWord(fs.getName(),"GB2312",null));
//防止文件名字中文乱码
mp.addBodyPart(mbp);
}
catch(Exception e){
JOptionPane.showMessageDialog(this,"附件增加出错"+e);
}
}
files.removeAllElements();
}
//工作方法:发送邮件给smtp服务器
public void doSend(){
//java mail 允许处理许多的属性Properities
Properties props=new Properties();
props.put("mail.smtp.host",smtpTF.getText());
props.put("mail.smtp.auth","true");
//Session
session=Session.getDefaultInstance(props,null);
session.setDebug(true); try{
mp=new MimeMultipart();//
//MIME message
mesg=new MimeMessage(session);
mesg.setFrom(new InternetAddress(userName.getText())); //To 地址//这里其实可以群发,用一个InternetAddress[],之后用mesg.addRecipients(..)
InternetAddress toAddress=new InternetAddress(recp.getText());
mesg.addRecipient(Message.RecipientType.TO,toAddress); //主题
mesg.setSubject(subject.getText()); //正文body支持html,自己写好看的脚本的啊
MimeBodyPart bp=new MimeBodyPart();
bp.setContent("<meta content=text/html; charset=gb2312>"+msg.getText(),"text/html;charset=GB2312");
mp.addBodyPart(bp);
//附件
if(!files.isEmpty()) affix();
mesg.setContent(mp);
mesg.saveChanges();
mesg.setSentDate(new Date()); //发送邮件
Transport transport = session.getTransport("smtp");
StringTokenizer tempName=new StringTokenizer(userName.getText(),"@");
transport.connect(smtpTF.getText(),tempName.nextToken(),passWord.getText());
transport.sendMessage(mesg,mesg.getRecipients(Message.RecipientType.TO));
JOptionPane.showMessageDialog(this,"邮件发送成功!"); }catch(Exception ex){
JOptionPane.showMessageDialog(this,"邮件发送失败,请检查网络或者参数"+ex);
}
} public static void main(String[] av){
JFrame.setDefaultLookAndFeelDecorated(true);
Sender sm=new Sender("javaMail for ESMTP");
//居中
Dimension screen=Toolkit.getDefaultToolkit().getScreenSize();
Dimension frame=sm.getSize();
int newX=(screen.width-frame.width)/2;
int newY=(screen.height-frame.height)/2;
sm.setLocation(newX,newY);
sm.show();
sm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
http://www.cn-java.com/target/news.php?news_id=3270
成功了
但是 public SendMail() {
setSmtpHost(getConfig.mailHost);//如果没有指定?件服?器,就从getConfig?中?取
createMimeMessage();
}
中的getConfig.mailHost怎么得到?下面是红线,编译不过去。
成功了
但是 public SendMail() {
setSmtpHost(getConfig.mailHost);//如果没有指定?件服?器,就从getConfig?中?取
createMimeMessage();
}
中的getConfig.mailHost怎么得到?下面是红线,编译不过去。
成功了
但是 public SendMail() {
setSmtpHost(getConfig.mailHost);//如果没有指定?件服?器,就从getConfig?中?取
createMimeMessage();
}
中的getConfig.mailHost怎么得到?下面是红线,编译不过去。
通过测试了
package jp.co.mitsubishielectric.buil.cscard.utils;import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Part;
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.MimeMessage;import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;import com.sun.mail.util.BASE64EncoderStream;public class MailUtil {
/** ログ出力 */
private static Log log = LogFactory.getLog(MailUtil.class.getName()); /** SMTPサーバのホスト名 */
static final String SMTP_HOST = CSCardProperties.SMTP_HOST; /** SMTPサーバのポート番号 */
static final String SMTP_PORT = CSCardProperties.SMTP_PORT; Session session = null; static MailUtil me = null; /**
* SMTP認証が必要な場合、認証情報を保持するオブジェクト
*
* @author u9-0046
* @version 1.00 2004/06/28
* @since
*/
private class MyAuth extends Authenticator { /**
* ユーザID
*/
String userid = ""; /**
* パスワード
*/
String password = ""; /**
* 認証情報を生成します。
*
* @param userid
* ユーザID
* @param password
* パスワード
*/
public MyAuth(String userid, String password) {
this.userid = userid;
this.password = password;
} /*
* (非 Javadoc)
*
* @see javax.mail.Authenticator#getPasswordAuthentication()
*/
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userid, password);
}
}
* Singltonを実装するためのインスタンス取得メソッド
*
* @return 唯一のMailUtilオブジェクト
*/
public static MailUtil getInstance() {
if (me == null) {
me = new MailUtil();
}
return me;
} /**
* コンストラクタ セッションの生成を行います。
*
*/
private MailUtil() {
if (log.isInfoEnabled()) {
log.info("MailUtil Creating");
}
Properties props = System.getProperties(); props.put("mail.smtp.host", SMTP_HOST);
props.put("mail.smtp.port", SMTP_PORT);
props.put("mail.mime.charset", "ISO-2022-JP");
props.put("mail.mime.decodetext.strict", "false");
props.put("mail.mime.address.strict", "false");
if(log.isDebugEnabled()){
props.put("mail.debug", "true");
}
Authenticator auth = null;
if ("true".equalsIgnoreCase(CSCardProperties.SMTP_AUTH)) {
props.put("mail.smtp.auth", "true");
auth = new MyAuth("murai", "pass");
} session = Session.getDefaultInstance(props, auth); if (log.isDebugEnabled()) {
session.setDebug(true);
} if (log.isInfoEnabled()) {
log.info("MailUtil Created");
}
} /**
* メールを送信します。
*
* @param fromAddress
* 送信元(FROM)のメールアドレス
* @param toAddress
* 送信先(TO)のメールアドレス(配列)
* @param ccAddress
* 写し先(CC)のメールアドレス(配列)
* @param bccAddress
* 匿名写し先(BCC)のメールアドレス(配列)
* @param subject
* メールの件名
* @param body
* メール本文
* @throws AddressException
* @throws MessagingException
* @throws UnsupportedEncodingException
*/
public void send(String fromAddress, String[] toAddress,
String[] ccAddress, String[] bccAddress, String subject, String body)
throws Exception {
if (log.isInfoEnabled()) {
log.info("MailUtil Sending");
}
MimeMessage msg = new MimeMessage(session);
// From
msg.setFrom(new InternetAddress(fromAddress));
// To
if (toAddress.length > 0) {
msg.setRecipients(Message.RecipientType.TO,
convertString2InternetAddress(toAddress));
}
// CC
if (ccAddress!=null) {
if (ccAddress.length > 0) {
msg.setRecipients(Message.RecipientType.CC,
convertString2InternetAddress(ccAddress));
}
}
// BCC-----------------------------------------------------
if (bccAddress!=null) {
if (bccAddress.length > 0) {
msg.setRecipients(Message.RecipientType.BCC,
convertString2InternetAddress(bccAddress));
}
}
// 件名(Subjects)
// 小文字のローマ数字が化けます。
if (subject.length() != 0) {
msg.setSubject(encodeWordJIS(subject));
// msg.setSubject(subject, "ISO-2022-JP");
}
// 本文(body)
// 対象はWindows端末
msg.setContent(body, "text/html; charset=Windows-31J");
// setTextContent(msg,body);
msg.setSentDate(new Date());
Transport.send(msg);
if (log.isInfoEnabled()) {
log.info("MailUtil Sended");
} }
/**
* メールを送信します。デフォルトのFromアドレスを用います。
*
* @param toAddress
* 送信先(TO)のメールアドレス(配列)
* @param ccAddress
* 写し先(CC)のメールアドレス(配列)
* @param bccAddress
* 匿名写し先(BCC)のメールアドレス(配列)
* @param subject
* メールの件名
* @param body
* メール本文
* @throws AddressException
* @throws MessagingException
* @throws UnsupportedEncodingException
*/
public void send(String[] toAddress, String[] ccAddress,
String[] bccAddress, String subject, String body)
throws Exception {
send(CSCardProperties.SMTP_FROM, toAddress, ccAddress, bccAddress,
subject, body);
} /**
* 文字列配列からメールアドレス配列へ変換します。
*
* @param fromAddr
* @return @throws
* AddressException
*/
private InternetAddress[] convertString2InternetAddress(String[] fromAddr)
throws AddressException {
InternetAddress[] toAddr = null;
if (fromAddr.length > 0) {
toAddr = new InternetAddress[fromAddr.length];
for (int i = 0; i < fromAddr.length; i++) {
toAddr[i] = new InternetAddress(fromAddr[i]);
}
}
return toAddr;
}
/**
* テキストをセットします。
* Part#setText() の代わりにこちらを使うようにします。
*/
public static void setTextContent(Part p, String s)
throws MessagingException {
p.setDataHandler(new DataHandler(new JISDataSource(s)));
p.setHeader("Content-Transfer-Encoding", "7bit");
} /**
* 日本語を含むヘッダ用テキストを生成します。
* 変換結果は ASCII なので、これをそのまま setSubject や InternetAddress
* のパラメタとして使用してください。
*/
public static String encodeWordJIS(String s) {
try {
return "=?ISO-2022-JP?B?" +
new String(
BASE64EncoderStream.encode(
CharCodeConverter.sjisToJis(
UnicodeCorrecter.correctToCP932(s)
.getBytes("Windows-31J")
)
)
) + "?=";
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("CANT HAPPEN");
}
}
}/**
* テキストの本文を送信するための DataSource です。
*/
class JISDataSource implements DataSource {
private byte[] data;
public JISDataSource(String s) {
try {
data = CharCodeConverter.sjisToJis(
UnicodeCorrecter.correctToCP932(s).getBytes("Windows-31J"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("CANT HAPPEN");
}
} public String getContentType() {
return "text/plain; charset=ISO-2022-JP";
}
public InputStream getInputStream() throws IOException {
if (data == null)
throw new IOException("no data");
return new ByteArrayInputStream(data);
}
public OutputStream getOutputStream() throws IOException {
throw new IOException("cannot do this");
}
public String getName() {
return "dummy";
}
}/**
* 文字関係のコンバータです。
* 一部コードのオリジナルは<a href="http://www-cms.phys.s.u-tokyo.ac.jp/~naoki/CIPINTRO/CCGI/kanjicod.html">Japanese Kanji Code</a>にて公開されているものです。
* また、http://www.sk-jp.com/cgi-bin/treebbs.cgi?kako=1&all=644&s=681
* にて YOSI さんが公開されたコードも参考にしています(というか実質同じです)。
*/
class CharCodeConverter {
public static final byte[] SJIS_KANA;
static {
try {
// 全角への変換テーブル
SJIS_KANA = "。「」、・ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゛゜".getBytes("Shift_JIS");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("CANT HAPPEN");
}
} /**
* Shift_JIS エンコーディングスキームに基づくバイト列を
* ISO-2022-JP エンコーディングスキームに変換します。
* 「半角カナ」は対応する全角文字に変換します。
*/
public static byte[] sjisToJis(byte[] sjisBytes) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
boolean nonAscii = false;
int len = sjisBytes.length;
for (int i = 0; i < len; i++ ) {
if (sjisBytes[i] >= 0) {
if (nonAscii) {
nonAscii = false;
out.write(0x1b);
out.write('(');
out.write('B');
}
out.write(sjisBytes[i]);
} else {
if (!nonAscii) {
nonAscii = true;
out.write(0x1b);
out.write('$');
out.write('B');
}
int b = sjisBytes[i] & 0xff;
if (b >= 0xa1 && b <= 0xdf) {
// 半角カナは全角に変換
int kanaIndex = (b - 0xA1) * 2;
sjisToJis(out, SJIS_KANA[kanaIndex], SJIS_KANA[kanaIndex + 1]);
} else {
i++;
if (i == len) break;
sjisToJis(out, sjisBytes[i - 1], sjisBytes[i]);
}
}
}
if (nonAscii) {
out.write(0x1b);
out.write('(');
out.write('B');
}
return out.toByteArray();
}
/**
* 1文字の2バイト Shift_JIS コードを JIS コードに変換して書き出します。
*/
private static void sjisToJis(
ByteArrayOutputStream out, byte bh, byte bl) {
int h = (bh << 1) & 0xFF;
int l = bl & 0xFF;
if (l < 0x9F) {
if (h < 0x3F) h += 0x1F; else h -= 0x61;
if (l > 0x7E) l -= 0x20; else l -= 0x1F;
} else {
if (h < 0x3F) h += 0x20; else h -= 0x60;
l -= 0x7E;
}
out.write(h);
out.write(l);
}
}
class UnicodeCorrecter {
/**
* Unicode 文字列の補正を行います。
* "MS932" コンバータでエンコードしようとした際に
* 正常に変換できない部分を補正します。
*/
public static String correctToCP932(String s) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < s.length(); i++) {
buf.append(correctToCP932(s.charAt(i)));
}
return new String(buf);
}
public static char correctToCP932(char c) {
switch (c) {
case 0x301c: // WAVE DASH ->
return 0xff5e; // FULLWIDTH TILDE
case 0x2016: // DOUBLE VERTICAL LINE ->
return 0x2225; // PARALLEL TO
case 0x2212: // MINUS SIGN ->
return 0xff0d; // FULLWIDTH HYPHEN-MINUS
}
return c;
}
}你只需要导入相应的包就可以了!