发送带图片邮件例子

本文介绍了一个使用Java实现的简单SMTP邮件发送程序。该程序利用JavaMail API构建并发送包含HTML内容和内联图片的电子邮件。此外,还展示了如何处理常见的异常情况,如认证失败或邮件发送失败。
package com.cellcom;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.SendFailedException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import com.sun.mail.smtp.SMTPAddressFailedException;
import com.sun.mail.smtp.SMTPAddressSucceededException;
import com.sun.mail.smtp.SMTPSendFailedException;
import com.sun.mail.smtp.SMTPTransport;

public class smtpsend {


    public static void main(String[] argv) {
	String   from = "name@example.com", url = null;
	String mailhost = "smtp.example.com";
	String mailer = "smtpsend";
	String protocol = null, host = "smtp.example.com", user = "name", password = "psd";
	String record = null;	// name of folder in which to record mail
	boolean debug = false;
	boolean verbose = false;
	boolean auth = true;
	String prot = "smtp";

	try {

	    Properties props = System.getProperties();
	    if (mailhost != null)
		props.put("mail." + prot + ".host", mailhost);
	    if (auth)
		props.put("mail." + prot + ".auth", "true");

	    Session session = Session.getInstance(props, null);
	    if (debug)
		session.setDebug(true);

	    Message msg = new MimeMessage(session);
	    if (from != null)
		msg.setFrom(new InternetAddress(from));
	    else
		msg.setFrom();

	    msg.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse("name@example.com", false));

	    msg.setSubject("dd");
	    MimeMultipart multipart = new MimeMultipart("related");

        BodyPart messageBodyPart = new MimeBodyPart();
        String htmlText = "<H1>Hello</H1><img src=\"cid:image\">ddddddd";
        String htmlText1 = "<H1>Hello</H1><img src=\"cid:image1\">ddddddd";
        messageBodyPart.setContent(htmlText + htmlText1, "text/html");

        multipart.addBodyPart(messageBodyPart);
        
        messageBodyPart = new MimeBodyPart();
        DataSource fds = new FileDataSource
          ("E:\\aa\\bb\\icons\\incomingLinksNavigatorGroup.gif");
        messageBodyPart.setDataHandler(new DataHandler(fds));
        messageBodyPart.setHeader("Content-ID","<image>");
        multipart.addBodyPart(messageBodyPart);
        messageBodyPart = new MimeBodyPart();
        fds = new FileDataSource
          ("E:\\aa\\bb\\icons\\incomingLinksNavigatorGroup.gif");
        messageBodyPart.setDataHandler(new DataHandler(fds));
        messageBodyPart.setHeader("Content-ID","<image1>");

        // add it
        multipart.addBodyPart(messageBodyPart);
        
        
		msg.setContent(multipart);
	    SMTPTransport t =
		(SMTPTransport)session.getTransport(prot);
	    try {
		if (auth)
		    t.connect(mailhost, user, password);
		else
		    t.connect();
		t.sendMessage(msg, msg.getAllRecipients());
	    } finally {
		if (verbose)
		    System.out.println("Response: " +
						t.getLastServerResponse());
		t.close();
	    }

	    System.out.println("\nMail was sent successfully.");

	    if (record != null) {
		// Get a Store object
		Store store = null;
		if (url != null) {
		    URLName urln = new URLName(url);
		    store = session.getStore(urln);
		    store.connect();
		} else {
		    if (protocol != null)		
			store = session.getStore(protocol);
		    else
			store = session.getStore();

		    // Connect
		    if (host != null || user != null || password != null)
			store.connect(host, user, password);
		    else
			store.connect();
		}
		Folder folder = store.getFolder(record);
		if (folder == null) {
		    System.err.println("Can't get record folder.");
		    System.exit(1);
		}
		if (!folder.exists())
		    folder.create(Folder.HOLDS_MESSAGES);

		Message[] msgs = new Message[1];
		msgs[0] = msg;
		folder.appendMessages(msgs);

		System.out.println("Mail was recorded successfully.");
	    }

	} catch (Exception e) {
	    if (e instanceof SendFailedException) {
		MessagingException sfe = (MessagingException)e;
		if (sfe instanceof SMTPSendFailedException) {
		    SMTPSendFailedException ssfe =
				    (SMTPSendFailedException)sfe;
		    System.out.println("SMTP SEND FAILED:");
		    if (verbose)
			System.out.println(ssfe.toString());
		    System.out.println("  Command: " + ssfe.getCommand());
		    System.out.println("  RetCode: " + ssfe.getReturnCode());
		    System.out.println("  Response: " + ssfe.getMessage());
		} else {
		    if (verbose)
			System.out.println("Send failed: " + sfe.toString());
		}
		Exception ne;
		while ((ne = sfe.getNextException()) != null &&
			ne instanceof MessagingException) {
		    sfe = (MessagingException)ne;
		    if (sfe instanceof SMTPAddressFailedException) {
			SMTPAddressFailedException ssfe =
					(SMTPAddressFailedException)sfe;
			System.out.println("ADDRESS FAILED:");
			if (verbose)
			    System.out.println(ssfe.toString());
			System.out.println("  Address: " + ssfe.getAddress());
			System.out.println("  Command: " + ssfe.getCommand());
			System.out.println("  RetCode: " + ssfe.getReturnCode());
			System.out.println("  Response: " + ssfe.getMessage());
		    } else if (sfe instanceof SMTPAddressSucceededException) {
			System.out.println("ADDRESS SUCCEEDED:");
			SMTPAddressSucceededException ssfe =
					(SMTPAddressSucceededException)sfe;
			if (verbose)
			    System.out.println(ssfe.toString());
			System.out.println("  Address: " + ssfe.getAddress());
			System.out.println("  Command: " + ssfe.getCommand());
			System.out.println("  RetCode: " + ssfe.getReturnCode());
			System.out.println("  Response: " + ssfe.getMessage());
		    }
		}
	    } else {
		System.out.println("Got Exception: " + e);
		if (verbose)
		    e.printStackTrace();
	    }
	}
    }

    public static String collect(BufferedReader in) throws IOException {
	String line;
	StringBuffer sb = new StringBuffer();
	while ((line = in.readLine()) != null) {
	    sb.append(line);
	    sb.append("\n");
	}
	return sb.toString();
    }
}
 
在Python中,我们可以使用smtplib和email库来发送邮件,如果需要包含图片,通常会将图片作为附件附在邮件里。以下是一个简单的例子: ```python import smtplib from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email.mime.text import MIMEText from email.utils import COMMASPACE, formatdate from email import encoders # 定义发件人、收件人和SMTP服务器等信息 sender = 'your_email@example.com' receiver = 'recipient_email@example.com' password = 'your_password' smtp_server = 'smtp.example.com' # 创建MIME对象 msg = MIMEMultipart() msg['From'] = sender msg['To'] = COMMASPACE.join(receiver) msg['Date'] = formatdate(localtime=True) # 邮件正文 text = MIMEText('这是一封图片邮件', 'plain') msg.attach(text) # 添加图片作为附件 with open('image.jpg', 'rb') as f: image = MIMEBase('image', 'jpeg') image.set_payload(f.read()) encoders.encode_base64(image) image.add_header('Content-Disposition', 'attachment', filename='image.jpg') msg.attach(image) # 连接SMTP服务器并发送邮件 try: server = smtplib.SMTP(smtp_server, 587) server.starttls() # 开启TLS加密 server.login(sender, password) server.sendmail(sender, receiver, msg.as_string()) print("邮件发送成功") except Exception as e: print("邮件发送失败: ", str(e)) # 关闭连接 server.quit() ``` 在这个示例中,你需要替换`sender`, `receiver`, `password`, 和`smtp_server`为你实际的邮箱和密码信息,以及图片文件路径。邮件正文部分可以自定义,图片文件应放在程序运行目录下。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值