❶ 用java来发送带附件的邮件
用java来发送带附件的邮件要翻译的。
❷ 急java 发送邮件 急!~急!~ 高手快进来帮忙看看啊!~
这是我的连续发几封邮件的代码。连续发是为了163邮箱的积分,^_^。你可以参考下。
package com.test;
import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class SendEmail extends Authenticator {
public static final String mailuser = "xianlaioy"; // 需要你的邮箱帐号(仅@符号前面的)
public static final String password = "######"; // 需要你的邮箱密码
private Properties props;
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(mailuser, password);
}
public SendEmail(){
props = new Properties();
InputStream is = null;
try {
/*当部署在web容器中时,路径要修改
* Thread.currentThread().getContextClassLoader().getResource("").getPath();
* 得到的url是web容器中的项目下的class路径
**/
is = new FileInputStream("src/sendemail.properties");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
props.load(is);
} catch (IOException e) {
e.printStackTrace();
}
}
/** email为接收邮箱,text为邮件正文
* @throws IOException */
public void sendEamils(String email, String text) throws IOException {
Transport transport = null;
try {
props.setProperty("mail.smtp.host", props.getProperty("mail.smtp.host"));
props.setProperty("mail.smtp.auth", props.getProperty("mail.smtp.auth"));
SendEmail auth = new SendEmail();
javax.mail.Session session = javax.mail.Session.getDefaultInstance(props,
auth);
MimeMessage message = new MimeMessage(session);
Address addressFrom = new InternetAddress(SendEmail.mailuser
+ "@163.com", "欧阳");
Address addressTo = new InternetAddress(email, "xianlai");
message.setText(text);
message.setSubject("邮件标题");
message.setFrom(addressFrom);
message.addRecipient(Message.RecipientType.TO, addressTo);
message.saveChanges();
transport = session.getTransport("smtp");
session.setDebug(true);
/*transport.connect("smtp.126.com", SendEmail.mailuser,
SendEmail.password);*/
transport.send(message);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} finally {
if (transport != null) {
try {
transport.close();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
Timer t = new Timer();
long delay =2*60*1000;
t.schele(new TimerTask(){
private int count=0;
private SendEmail se=new SendEmail();//作为成员变量就只会创建一个SendEmail对象。
public void run() {
//在timer的run中就必须考虑好怎样或者什么时候退出的问题。
//这里是用count计数的方法来考虑退出的问题的。
if(count++<1){
int i=10;
for (int j = 0; j < i; j++) {
try {
se.sendEamils("[email protected]","test"+j );
} catch (IOException e) {
e.printStackTrace();
}
}
}else {
this.cancel();
System.exit(0);
}
}}, 2000,delay);
}
}
❸ java里如何判断Email是否发送成功
package com.liuns.mail.test;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
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 MailTest {
//发送的邮箱 内部代码只适用qq邮箱
private static final String USER = "[email protected]";
//授权密码 通过QQ邮箱设置->账户->POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务->开启POP3/SMTP服务获取
private static final String PWD = "xxx";
private String[] to;
private String[] cc;//抄送
private String[] bcc;//密送
private String[] fileList;//附件
private String subject;//主题
private String content;//内容,可以用html语言写
public void sendMessage() throws Exception {
// 配置发送邮件的环境属性
final Properties props = new Properties();
//下面两段代码是设置ssl和端口,不设置发送不出去。
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
//props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
// 表示SMTP发送邮件,需要进行身份验证
props.setProperty("mail.transport.protocol", "smtp");// 设置传输协议
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.qq.com");//QQ邮箱的服务器 如果是企业邮箱或者其他邮箱得更换该服务器地址
// 发件人的账号
props.put("mail.user", USER);
// 访问SMTP服务时需要提供的密码
props.put("mail.password", PWD);
// 构建授权信息,用于进行SMTP进行身份验证
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// 用户名、密码
String userName = props.getProperty("mail.user");
String password = props.getProperty("mail.password");
return new PasswordAuthentication(userName, password);
}
};
// 使用环境属性和授权信息,创建邮件会话
Session mailSession = Session.getInstance(props, authenticator);
// 创建邮件消息
MimeMessage message = new MimeMessage(mailSession);
BodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
// 设置发件人
InternetAddress form = new InternetAddress(
props.getProperty("mail.user"));
message.setFrom(form);
//发送
if (to != null) {
String toList = getMailList(to);
InternetAddress[] iaToList = new InternetAddress().parse(toList);
message.setRecipients(RecipientType.TO, iaToList); // 收件人
}
//抄送
if (cc != null) {
String toListcc = getMailList(cc);
InternetAddress[] iaToListcc = new InternetAddress().parse(toListcc);
message.setRecipients(RecipientType.CC, iaToListcc); // 抄送人
}
//密送
if (bcc != null) {
String toListbcc = getMailList(bcc);
InternetAddress[] iaToListbcc = new InternetAddress().parse(toListbcc);
message.setRecipients(RecipientType.BCC, iaToListbcc); // 密送人
}
message.setSentDate(new Date()); // 发送日期 该日期可以随意写,你可以写上昨天的日期(效果很特别,亲测,有兴趣可以试试),或者抽象出来形成一个参数。
message.setSubject(subject); // 主题
message.setText(content); // 内容
//显示以html格式的文本内容
messageBodyPart.setContent(content,"text/html;charset=utf-8");
multipart.addBodyPart(messageBodyPart);
//保存多个附件
if(fileList!=null){
addTach(fileList, multipart);
}
message.setContent(multipart);
// 发送邮件
Transport.send(message);
}
public void setTo(String[] to) {
this.to = to;
}
public void setCc(String[] cc) {
this.cc = cc;
}
public void setBcc(String[] bcc) {
this.bcc = bcc;
}
public void setSubject(String subject) {
this.subject = subject;
}
public void setContent(String content) {
this.content = content;
}
public void setFileList(String[] fileList) {
this.fileList = fileList;
}
private String getMailList(String[] mailArray) {
StringBuffer toList = new StringBuffer();
int length = mailArray.length;
if (mailArray != null && length < 2) {
toList.append(mailArray[0]);
} else {
for (int i = 0; i < length; i++) {
toList.append(mailArray[i]);
if (i != (length - 1)) {
toList.append(",");
}
}
}
return toList.toString();
}
//添加多个附件
public void addTach(String fileList[], Multipart multipart) throws Exception {
for (int index = 0; index < fileList.length; index++) {
MimeBodyPart mailArchieve = new MimeBodyPart();
FileDataSource fds = new FileDataSource(fileList[index]);
mailArchieve.setDataHandler(new DataHandler(fds));
mailArchieve.setFileName(MimeUtility.encodeText(fds.getName(),"UTF-8","B"));
multipart.addBodyPart(mailArchieve);
}
}
//以下是演示demo
public static void main(String args[]) {
MailTest mail = new MailTest();
mail.setSubject("java邮件");
mail.setContent("你好 这是第一个java 程序发送邮件");
//收件人 可以发给其他邮箱(163等) 下同
mail.setTo(new String[] {"[email protected]"});
//抄送
// mail.setCc(new String[] {"[email protected]","[email protected]"});
//密送
//mail.setBcc(new String[] {"[email protected]","[email protected]"});
//发送附件列表 可以写绝对路径 也可以写相对路径(起点是项目根目录)
// mail.setFileList(new String[] {"D:\\aa.txt"});
//发送邮件
try {
mail.sendMessage();
System.out.println("发送邮件成功!");
} catch (Exception e) {
System.out.println("发送邮件失败!");
e.printStackTrace();
}
}
}
❹ java中如何实现公司邮箱发送邮件配置
Java中可以通过Javamail API实现公司邮箱邮件发送配置,Java mail是利用现有的邮箱账户发送邮件的版工具,具体步权骤如如下:
1、通过JavamailAPI设置发送者邮箱用户名及密码
2、通过JavamailAPI设置邮件主题、邮件内容、附件及邮件发送时间
3、通过JavamailAPI设置发送者邮箱地址及接收者邮箱地址,接收者地址可以是多个及抄送
4、邮件的需基本元素都设置完毕后,即可通过Javamail API的发送接口执行发送操作。
❺ java实现发送邮件功能
要实现邮件发送功能需要导入包:mail.jar
/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package org.demo.action;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
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 org.demo.form.DemoForm;
public class DemoAction extends Action {
private static final String CONTENT_TYPE = "test/html;charset=GB2312";
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
DemoForm demoForm = (DemoForm) form;
System.out.println("标题是" + demoForm.getBiaoti());
System.out.println("内容是" + demoForm.getNeirong());
try {
response.setContentType(CONTENT_TYPE);
String smtphost = "smtp.nj.headware.cn"; // 发送邮件服务器
String user = "q0000015369"; // 邮件服务器登录用户名
String password = "Queshuwen26"; // 邮件服务器登录密码
String from = "[email protected]"; //
String to = "[email protected]"; // 收件人邮件地址
String subject = demoForm.getBiaoti(); // 邮件标题
String body = demoForm.getNeirong(); // 邮件内容
Properties props = new Properties();
props.put("mail.smtp.host", smtphost);
props.put("mail.smtp.auth", "true");
Session ssn = Session.getInstance(props, null);
MimeMessage message = new MimeMessage(ssn);
InternetAddress fromAddress = new InternetAddress(from);
message.setFrom(fromAddress);
InternetAddress toAddress = new InternetAddress(to);
message.addRecipient(Message.RecipientType.TO, toAddress);
message.setSubject(subject);
message.setText(body);
Transport transport = ssn.getTransport("smtp");
transport.connect(smtphost, user, password);
transport.sendMessage(message, message
.getRecipients(Message.RecipientType.TO));
// transport.send(message);
transport.close();
return mapping.findForward("succ");
} catch (Exception e) {
e.printStackTrace();
return mapping.findForward("fail");
}
}
}
❻ 如何使用Java发送qq邮件
方法:
1.前提准备工作:
首先,邮件的发送方要开启POP3 和SMTP服务--即发送qq邮件的账号要开启POP3 和SMTP服务
2.开启方法:
登陆qq邮箱
3.点击 设置
4.点击—-账户
5.找到:POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务 —点击开启
6.送短信 —–点击确定
7.稍等一会,很得到一个授权码! –注意:这个一定要记住,一会用到
8.点击保存修改 —OK 完成
9.java 测试代码:
package cn.cupcat.test;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
public class SendmailUtil {
public static void main(String[] args) throws AddressException, MessagingException {
Properties properties = new Properties();
properties.put("mail.transport.protocol", "smtp");// 连接协议
properties.put("mail.smtp.host", "smtp.qq.com");// 主机名
properties.put("mail.smtp.port", 465);// 端口号
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.ssl.enable", "true");//设置是否使用ssl安全连接 ---一般都使用
properties.put("mail.debug", "true");//设置是否显示debug信息 true 会在控制台显示相关信息
//得到回话对象
Session session = Session.getInstance(properties);
// 获取邮件对象
Message message = new MimeMessage(session);
//设置发件人邮箱地址
message.setFrom(new InternetAddress("[email protected]"));
//设置收件人地址 message.setRecipients( RecipientType.TO, new InternetAddress[] { new InternetAddress("[email protected]") });
//设置邮件标题
message.setSubject("这是第一封Java邮件");
//设置邮件内容
message.setText("内容为: 这是第一封java发送来的邮件。");
//得到邮差对象
Transport transport = session.getTransport();
//连接自己的邮箱账户
transport.connect("[email protected]", "vvctybgbvvophjcj");//密码为刚才得到的授权码
//发送邮件 transport.sendMessage(message, message.getAllRecipients());
}
}
10.运行就会发出邮件了。。。。
下面是我收到邮件的截图,当然我把源码中的邮件地址都是修改了,不是真实的,你们测试的时候,可以修改能你们自己的邮箱。最后,祝你也能成功,如果有什么问题,可以一起讨论!
注意事项
得到的授权码一定要保存好,程序中要使用
❼ 如何用java实现发送html格式的邮件
首先Java发送邮件需要用到JavaMail,先到Oracle官网上下载好最新版本的JavaMail(刚才看了一下,最新是1.5.3),把下载的这个jar文件放到classpath里(如果是Web项目,就放到WEB-INF/lib目录下。
JavaMail主要支持发送纯文本的和html格式的邮件。
发送html格式的邮件的一个例程如下:
importjavax.mail.internet.InternetAddress;
importjavax.mail.internet.MimeMessage;
importjavax.mail.internet.MimeUtility;
importjavax.mail.Session;
importjavax.mail.MessagingException;
importjavax.mail.Transport;
publicclassSendHtmlMail{
publicstaticvoidsendMessage(StringsmtpHost,
Stringfrom,Stringto,
Stringsubject,StringmessageText)
throwsMessagingException,java.io.UnsupportedEncodingException{
//Step1:Configurethemailsession
System.out.println("Configuringmailsessionfor:"+smtpHost);
java.util.Propertiesprops=newjava.util.Properties();
props.setProperty("mail.smtp.auth","true");//指定是否需要SMTP验证
props.setProperty("mail.smtp.host",smtpHost);//指定SMTP服务器
props.put("mail.transport.protocol","smtp");
SessionmailSession=Session.getDefaultInstance(props);
mailSession.setDebug(true);//是否在控制台显示debug信息
//Step2:Constructthemessage
System.out.println("Constructingmessage-from="+from+"to="+to);
InternetAddressfromAddress=newInternetAddress(from);
InternetAddresstoAddress=newInternetAddress(to);
MimeMessagetestMessage=newMimeMessage(mailSession);
testMessage.setFrom(fromAddress);
testMessage.addRecipient(javax.mail.Message.RecipientType.TO,toAddress);
testMessage.setSentDate(newjava.util.Date());
testMessage.setSubject(MimeUtility.encodeText(subject,"gb2312","B"));
testMessage.setContent(messageText,"text/html;charset=gb2312");
System.out.println("Messageconstructed");
//Step3:Nowsendthemessage
Transporttransport=mailSession.getTransport("smtp");
transport.connect(smtpHost,"webmaster","password");
transport.sendMessage(testMessage,testMessage.getAllRecipients());
transport.close();
System.out.println("Messagesent!");
}
publicstaticvoidmain(String[]args){
StringsmtpHost="localhost";
Stringfrom="[email protected]";
Stringto="[email protected]";
Stringsubject="html邮件测试";//subjectjavamail自动转码
StringBuffertheMessage=newStringBuffer();
theMessage.append("<h2><fontcolor=red>这倒霉孩子</font></h2>");
theMessage.append("<hr>");
theMessage.append("<i>年年失望年年望</i>");
try{
SendHtmlMail.sendMessage(smtpHost,from,to,subject,theMessage.toString());
}
catch(javax.mail.MessagingExceptionexc){
exc.printStackTrace();
}
catch(java.io.){
exc.printStackTrace();
}
}
}
JavaMail是封装了很多邮件操作的,所以使用起来不很困难,建议你到JavaMail官网看一下API或下载Java Doc API文档。
❽ java发送邮件could not connect to smtp host port 25
这个错误是连不上邮件服务器的25端口。
1,检查邮件服务器是否正常,检查IP和端口是否写对。
2,检查你的主机到邮件服务器网络是否正常,可以用PING 或 TELNET IP PORT来测试。
❾ 用java写一个邮件发送代码
public boolean mainto()
{
boolean flag = true;
//建立邮件会话
Properties pro = new Properties();
pro.put("mail.smtp.host","smtp.qq.com");//存储发送邮件的服务器
pro.put("mail.smtp.auth","true"); //通过服务器验证
Session s =Session.getInstance(pro); //根据属性新建一个邮件会话
//s.setDebug(true);
//由邮件会话新建一个消息对象
MimeMessage message = new MimeMessage(s);
//设置邮件
InternetAddress fromAddr = null;
InternetAddress toAddr = null;
try
{
fromAddr = new InternetAddress(451144426+"@qq.com"); //邮件发送地址
message.setFrom(fromAddr); //设置发送地址
toAddr = new InternetAddress("[email protected]"); //邮件接收地址
message.setRecipient(Message.RecipientType.TO, toAddr); //设置接收地址
message.setSubject(title); //设置邮件标题
message.setText(content); //设置邮件正文
message.setSentDate(new Date()); //设置邮件日期
message.saveChanges(); //保存邮件更改信息
Transport transport = s.getTransport("smtp");
transport.connect("smtp.qq.com", "451144426", "密码"); //服务器地址,邮箱账号,邮箱密码
transport.sendMessage(message, message.getAllRecipients()); //发送邮件
transport.close();//关闭
}
catch (Exception e)
{
e.printStackTrace();
flag = false;//发送失败
}
return flag;
}
这是一个javaMail的邮件发送代码,需要一个mail.jar