java mail发送复杂邮件代码(包括附件,html消息,纯文本消息)

import  java.io.File;
import  java.util.Date;
import  java.util.Properties;

import  javax.activation.DataHandler;
import  javax.activation.DataSource;
import  javax.activation.FileDataSource;
import  javax.mail.Authenticator;
import  javax.mail.BodyPart;
import  javax.mail.Message;
import  javax.mail.MessagingException;
import  javax.mail.Multipart;
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.MimeBodyPart;
import  javax.mail.internet.MimeMessage;
import  javax.mail.internet.MimeMultipart;

/**
 * java mail 发送复杂邮件,包括两个附件,html消息,html中嵌入两张图片
 * 还包括发送alternative邮件的源码.
 * 
@author zhangle
 *
 
*/

public   class  SendMixedMail  {
    
//以下属性根据自己情况设置.
    private static String protocol="smtp";
    
private static String from="xxxx@163.com";
    
private static String to="xxxx@163.com";
    
private static String body="<html><body><a href='http://www.csdn.net'>I love you! csdn </a><img src='cid:img1'/><img src='cid:img2'/></body></html>";
    
private static String subject="mail test";
    
private static String server="smtp.163.com";
    
private static String username="your_name";//from mail name
    
private static String password="your_password";//from mail password
    
    
public static void main(String[] args) throws Exception, MessagingException {
        Properties prop
=new Properties();
        prop.setProperty(
"mail.transport.protocol",protocol);
        prop.setProperty(
"mail.smtp.auth","true");
        
        Session session
=Session.getInstance(prop,new Authenticator(){//用户连接认证
            public PasswordAuthentication getPasswordAuthentication() {
                
return new PasswordAuthentication(username,password);
            }

        }
);
        session.setDebug(
true);//开启调试
        
        MimeMessage message
=new MimeMessage(session);
        message.setFrom(
new InternetAddress(from));
        message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));
        message.setSubject(subject);
        message.setSentDate(
new Date());
        
//message.setText(body);//发送纯文本消息
        
//message.setContent(getAlternativeMultipart());//发送alternative邮件
        message.setContent(getMultipart());//发送复杂文本消息
        message.saveChanges();//保存消息
        
        Transport trans
=session.getTransport();
        trans.connect(server,username,password);
        trans.sendMessage(message,message.getRecipients(Message.RecipientType.TO));
//发送
        trans.close();
    }

    
/**
     * 获得复杂邮件Multipart对象
     * 
@return
     * 
@throws MessagingException
     
*/

    
private static Multipart getMultipart() throws MessagingException {
        
        Multipart multi
=new MimeMultipart("mixed");//混合MIME消息
        
        multi.addBodyPart(createContent());
        multi.addBodyPart(createAttachment(
new File("D:/test1.exe")));//嵌入附件
        multi.addBodyPart(createAttachment(new File("D:/test2.jpg")));
        
        
return multi;
        
    }

    
/**
     * 创建正文
     * 
@return
     * 
@throws MessagingException
     
*/

    
private static BodyPart createContent() throws MessagingException {
        BodyPart content
=new MimeBodyPart();
        Multipart relate
=new MimeMultipart("related");//组合MIME消息

        relate.addBodyPart(createHtmlBody());
        relate.addBodyPart(createImagePart(
new File("D:/image1.jpg"), "img1"));//嵌入图片
        relate.addBodyPart(createImagePart(new File("D:/image2.jpg"), "img2"));
        
        content.setContent(relate);
        
return content;
    }

    
    
/**
     * 创建图片
     * 
@param file
     * 
@param name
     * 
@return
     * 
@throws MessagingException
     
*/

    
private static BodyPart createImagePart(File file,String name) throws MessagingException {
        MimeBodyPart image
=new MimeBodyPart();
        
        DataSource ds
=new FileDataSource(file);
        image.setDataHandler(
new DataHandler(ds));
        image.setFileName(name);
        image.setContentID(name);
        
        
return image;
    }

    
/**
     * 创建html消息
     * 
@return
     * 
@throws MessagingException
     
*/

    
private static BodyPart createHtmlBody() throws MessagingException {
        BodyPart html
=new MimeBodyPart();
        html.setContent(body, 
"text/html;charset=gbk");
        
return html;
    }

    
/**
     * 创建附件
     * 
@param file
     * 
@return
     * 
@throws MessagingException
     
*/

    
private static BodyPart createAttachment(File file) throws MessagingException {
        BodyPart attach
=new MimeBodyPart();
        DataSource ds
=new FileDataSource(file);

        attach.setDataHandler(
new DataHandler(ds));
        attach.setFileName(ds.getName());

        
return attach;
    }

    
/**
     * 获取alternative邮件
     * 
@return
     * 
@throws MessagingException
     
*/

    
private static Multipart getAlternativeMultipart() throws MessagingException {

        Multipart alternative
=new MimeMultipart("alternative");//二选一消息
        
        BodyPart text
=new MimeBodyPart();
        text.setContent(
"请浏览HTML""text/plain;charset=gbk");
        alternative.addBodyPart(text);
        
        BodyPart html
=new MimeBodyPart();
        html.setContent(body, 
"text/html;charset=gbk");
        alternative.addBodyPart(html);

        
return alternative;
    }

}

 
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
#include <windows.h> #include <winsock.h> #include <assert.h> #include <iostream> #include <string> #include <stdio.h> #include <ctime> #pragma comment(lib,"WS2_32.lib") using namespace std; //base64编码 string Base64Encode(LPCTSTR lpszSrc); //base64解码 string Base64Decode(LPCTSTR lpszSrc); int main() { //1.首先需要连接邮件服务器 这里用socket 邮件服务器端口 25 WSADATA Wsa; //进行WINSOCK的设置 WSAStartup(0x0101,&Wsa); SOCKET s = socket(AF_INET,SOCK_STREAM,IPPROTO_IP); SOCKADDR_IN sin; LPHOSTENT lphost = gethostbyname("smtp.163.com");//这里是用网易的邮件服务器 也可以修改 if(lphost) sin.sin_addr.s_addr = ((LPIN_ADDR)lphost->h_addr)->s_addr; else { printf("%s\n","获取地址失败"); return 1; } sin.sin_family = AF_INET; //注意邮件服务器的侦听端口 25 sin.sin_port = htons(IPPORT_SMTP); //连接服务器 if(connect(s,(LPSOCKADDR)&sin,sizeof(sin))==SOCKET_ERROR) { printf("%s\n","连接错误"); return 1; } printf("%s\n","连接成功"); //接收服务器初次回应 char buff[1024]; memset(buff,0,sizeof(buff)); recv(s,buff,sizeof(buff),0); printf("服务说:%s\n",buff); /////上面已经完成连接了///// string szLine="\r\n";//相当于你按下回车 //2.现在就是和服务器对话了 //问候服务器 string szHelo = "HELO smtp.163.com" + szLine; printf("我说:%s\n",szHelo.c_str()); send(s,szHelo.c_str(),szHelo.length(),0); memset(buff,0,sizeof(buff)); recv(s,buff,sizeof(buff),0); printf("服务说:%s\n",buff); //请求验证用户密码(需要编码) string szAL = "auth login" + szLine; //发送验证命令 printf("我说:%s\n",szAL.c_str()); send(s,szAL.c_str(),szAL.length(),0); memset(buff,0,sizeof(buff)); recv(s,buff,sizeof(buff),0); // printf("服务说:%s\n",buff); //服务器会回答说 可以输入帐号 //发送帐号 string szUser; cout<<Base64Decode((LPCTSTR)(buff+4)); cin>>szUser; szUser = Base64Encode(szUser.c_str()) + szLine; //对输入的帐号进行base64编码 send(s,szUser.c_str(),szUser.length(),0); //发送帐号 printf("我说:%s\n",szUser.c_str()); memset(buff,0,sizeof(buff)); recv(s,buff,sizeof(buff),0); // printf("服务说:%s\n",buff); //服务器会回答说 可以输入密码 //发送密码 string szPsw; cout<<Base64Decode((LPCTSTR)(buff+4)); cin>>szPsw; szPsw = Base64Encode(szPsw.c_str()) + szLine; //对输入的密码进行base64编码 send(s,szPsw.c_str(),szPsw.length(),0); //发送密码 printf("我说:%s\n",szPsw.c_str()); memset(buff,0,sizeof(buff)); recv(s,buff,sizeof(buff),0); printf("服务说:%s\n",buff); //然后可以用你登陆的邮箱给其他邮箱发邮件了 string szFrom,szTo; cout<<"from:";//你自己的邮箱 cin>>szFrom; cout<<"to:"; //发送给谁 cin>>szTo; //发送者的地址 string From = "mail from:<"+szFrom+ ">"+ szLine; //收信者地址 string To = "rcpt to:<" + szTo +">" + szLine; //现在确定看谁发的邮件 往哪发 send(s,From.c_str(),From.length(),0);//from printf("我说:%s\n",From.c_str()); memset(buff,0,sizeof(buff)); recv(s,buff,sizeof(buff),0); printf("服务说:%s\n",buff); getchar(); //只是用来暂停一下而已 按任意字母继续 send(s,To.c_str(),To.length(),0); //to printf("我说:%s\n",To.c_str()); memset(buff,0,sizeof(buff)); recv(s,buff,sizeof(buff),0); printf("服务说:%s\n",buff); getchar(); //资料应该都看过了吧命令里的data输入后 表示输入邮件内容了 send(s,"data\r\n",6,0); //DATA 命令发送 printf("我说:%s\n","data"); memset(buff,0,sizeof(buff)); recv(s,buff,sizeof(buff),0); printf("服务说:%s\n",buff); //邮件 下面的信息都是当作内容处理 //邮件头 string szFrom_in = "from:"+szFrom + szLine; string szTo_in = "to:"+szTo + szLine; //发送日期 string szDate_in="Date: Sat, 20 Aug 2011 13:39:29 +0800" + szLine;//这里我就直接写上去日期了 为了方便 //邮件标题 string szSubject_in = "Subject:我是邮件标题" + szLine; //邮件正文 string szBody_in = "我就是传说中的邮件体" + szLine; string szContent = szFrom_in + szTo_in + szDate_in + szSubject_in; szContent += szLine;//添加一个空白行 szContent += szBody_in; //上面是最基本的格式// send(s,szContent.c_str(),szContent.length(),0); //szContent printf("我说:%s\n",szContent.c_str()); memset(buff,0,sizeof(buff)); // recv(s,buff,sizeof(buff),0); // printf("服务说:%s\n",buff); getchar(); //发送完了说明下结束 send(s,".\r\n",3,0); //说明内容结束了 printf("我说:%s\n","."); memset(buff,0,sizeof(buff)); recv(s,buff,sizeof(buff),0); printf("服务说:%s\n",buff); getchar(); //退出服务器连接 send(s,"quit\r\n",6,0); //退出 printf("我说:%s\n","quit"); memset(buff,0,sizeof(buff)); recv(s,buff,sizeof(buff),0); printf("服务说:%s 发送邮件成功\n",buff); return 0; } 等等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值