package comvictor;
import javaioFile;
import javaioIOException;
import javaioInputStream;
import javautilProperties;
import javaxactivationDataHandler;
import javaxactivationDataSource;
import javaxactivationFileDataSource;
import javaxmailBodyPart;
import javaxmailMessage;
import javaxmailMessagingException;
import javaxmailMultipart;
import javaxmailSession;
import javaxmailTransport;
import javaxmailinternetInternetAddress;
import javaxmailinternetMimeBodyPart;
import javaxmailinternetMimeMessage;
import javaxmailinternetMimeMultipart;
import javaxmailinternetMimeUtility;
public class JavaMailWithAttachment {
private MimeMessage message;
private Session session;
private Transport transport;
private String mailHost = "";
private String sender_username = "";
private String sender_password = "";
private Properties properties = new Properties();
/
初始化方法
/
public JavaMailWithAttachment(boolean debug) {
InputStream in = JavaMailWithAttachmentclassgetResourceAsStream("/MailServerproperties");
try {
propertiesload(in);
thismailHost = propertiesgetProperty("mailsmtphost");
thissender_username = propertiesgetProperty("mailsenderusername");
thissender_password = propertiesgetProperty("mailsenderpassword");
} catch (IOException e) {
eprintStackTrace();
}
session = SessiongetInstance(properties);
sessionsetDebug(debug);//开启后有调试信息
message = new MimeMessage(session);
}
/
发送邮件
@param subject
邮件主题
@param sendHtml
邮件内容
@param receiveUser
收件人地址
@param attachment
附件
/
public void doSendHtmlEmail(String subject, String sendHtml, String receiveUser, File attachment) {
try {
// 发件人
InternetAddress from = new InternetAddress(sender_username);
messagesetFrom(from);
// 收件人
InternetAddress to = new InternetAddress(receiveUser);
messagesetRecipient(MessageRecipientTypeTO, to);
// 邮件主题
messagesetSubject(subject);
// 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
Multipart multipart = new MimeMultipart();
// 添加邮件正文
BodyPart contentPart = new MimeBodyPart();
contentPartsetContent(sendHtml, "text/html;charset=UTF-8");
multipartaddBodyPart(contentPart);
// 添加附件的内容
if (attachment != null) {
BodyPart attachmentBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(attachment);
attachmentBodyPartsetDataHandler(new DataHandler(source));
// 网上流传的解决文件名乱码的方法,其实用MimeUtilityencodeWord就可以很方便的搞定
// 这里很重要,通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码
//sunmiscBASE64Encoder enc = new sunmiscBASE64Encoder();
//messageBodyPartsetFileName("=GBKB" + encencode(attachmentgetName()getBytes()) + "=");
//MimeUtilityencodeWord可以避免文件名乱码
attachmentBodyPartsetFileName(MimeUtilityencodeWord(attachmentgetName()));
multipartaddBodyPart(attachmentBodyPart);
}
// 将multipart对象放到message中
messagesetContent(multipart);
// 保存邮件
messagesaveChanges();
transport = sessiongetTransport("smtp");
// smtp验证,就是你用来发邮件的邮箱用户名密码
transportconnect(mailHost, sender_username, sender_password);
// 发送
transportsendMessage(message, messagegetAllRecipients());
Systemoutprintln("send success!");
} catch (Exception e) {
eprintStackTrace();
} finally {
if (transport != null) {
try {
transportclose();
} catch (MessagingException e) {
eprintStackTrace();
}
}
}
}
public static void main(String[] args) {
JavaMailWithAttachment se = new JavaMailWithAttachment(true);
Systemoutprintln(se);
File affix = new File("E:\\测试-testtxt");
// File affix =null;
sedoSendHtmlEmail("##", "###", "####@##com", affix);//
}
}
注意点:1 jar可能有冲突,如果是demo可以直接应用mailjar
如果是一个工程则要替换javaEE中的mailjar包
2 关于properties配置文件的地址问题
ClassgetResourceAsStream(String path) : path 不以’/'开头时默认是从此类所在的包下取资源,以’/'开头则是从
ClassPath根下获取。其只是通过path构造一个绝对路径,最终还是由ClassLoader获取资源。
首先Java发送邮件需要用到JavaMail,先到Oracle官网上下载好最新版本的JavaMail(刚才看了一下,最新是153),把下载的这个jar文件放到classpath里(如果是Web项目,就放到WEB-INF/lib目录下。
JavaMail主要支持发送纯文本的和html格式的邮件。
发送html格式的邮件的一个例程如下:
import javaxmailinternetInternetAddress;import javaxmailinternetMimeMessage;
import javaxmailinternetMimeUtility;
import javaxmailSession;
import javaxmailMessagingException;
import javaxmailTransport;
public class SendHtmlMail {
public static void sendMessage(String smtpHost,
String from, String to,
String subject, String messageText)
throws MessagingException,javaioUnsupportedEncodingException {
// Step 1: Configure the mail session
Systemoutprintln("Configuring mail session for: " + smtpHost);
javautilProperties props = new javautilProperties();
propssetProperty("mailsmtpauth", "true");//指定是否需要SMTP验证
propssetProperty("mailsmtphost", smtpHost);//指定SMTP服务器
propsput("mailtransportprotocol", "smtp");
Session mailSession = SessiongetDefaultInstance(props);
mailSessionsetDebug(true);//是否在控制台显示debug信息
// Step 2: Construct the message
Systemoutprintln("Constructing message - from=" + from + " to=" + to);
InternetAddress fromAddress = new InternetAddress(from);
InternetAddress toAddress = new InternetAddress(to);
MimeMessage testMessage = new MimeMessage(mailSession);
testMessagesetFrom(fromAddress);
testMessageaddRecipient(javaxmailMessageRecipientTypeTO, toAddress);
testMessagesetSentDate(new javautilDate());
testMessagesetSubject(MimeUtilityencodeText(subject,"gb2312","B"));
testMessagesetContent(messageText, "text/html;charset=gb2312");
Systemoutprintln("Message constructed");
// Step 3: Now send the message
Transport transport = mailSessiongetTransport("smtp");
transportconnect(smtpHost, "webmaster", "password");
transportsendMessage(testMessage, testMessagegetAllRecipients());
transportclose();
Systemoutprintln("Message sent!");
}
public static void main(String[] args) {
String smtpHost = "localhost";
String from = "webmaster@mymailcom";
String to = "mfc42d@sohucom";
String subject = "html邮件测试"; //subject javamail自动转码
StringBuffer theMessage = new StringBuffer();
theMessageappend("<h2><font color=red>这倒霉孩子</font></h2>");
theMessageappend("<hr>");
theMessageappend("<i>年年失望年年望</i>");
try {
SendHtmlMailsendMessage(smtpHost, from, to, subject, theMessagetoString());
}
catch (javaxmailMessagingException exc) {
excprintStackTrace();
}
catch (javaioUnsupportedEncodingException exc) {
excprintStackTrace();
}
}
}
JavaMail是封装了很多邮件 *** 作的,所以使用起来不很困难,建议你到JavaMail官网看一下API或下载Java Doc API文档。
1,去读一读SMTP协议的命令。command not implemented 说明是不支持的命令。建议你先到DOS下,或者其他工具,telnet 服务器IP 25
的界面下,可以发送了,再来写程序
2,Java发送邮件,用JMail吧。
import javaxmail;
import javaxmailinternet;
import javautil;
import javaio;
public class POP3Client {
public static void main(String[] args) {
Properties props = new Properties();
String host = "utopiapolyedu";
String username = "eharold";
String password = "mypassword";
String provider = "pop3";
try {
// Connect to the POP3 server
Session session = SessiongetDefaultInstance(props, null);
Store store = sessiongetStore(provider);
storeconnect(host, username, password);
// Open the folder
Folder inbox = storegetFolder("INBOX");
if (inbox == null) {
Systemoutprintln("No INBOX");
Systemexit(1);
}
inboxopen(FolderREAD_ONLY);
// Get the messages from the server
Message[] messages = inboxgetMessages();
for (int i = 0; i < messageslength; i++) {
Systemoutprintln("------------ Message " + (i+1)
+ " ------------");
messages[i]writeTo(Systemout);
}
// Close the connection
// but don't remove the messages from the server
inboxclose(false);
storeclose();
} catch (Exception ex) {
exprintStackTrace();
}
}
}
以上就是关于如何用java实现发邮件功能,并有几点注意事项全部的内容,包括:如何用java实现发邮件功能,并有几点注意事项、如何用java实现发送html格式的邮件、Java 邮件发送程序等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)