⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 htmlmessagesender.java

📁 关于JAVA邮件开发的源代码...很有参考价值的源代码
💻 JAVA
字号:
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
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;
public class HtmlMessageSender 
{
    String protocol = "smtp";
    String from = "it315_test@sina.com";
    String to = "it315_test@sohu.com ";
    String subject = "HTML测试";
    String body = "<a href=http://www.it315.org>" +
	 				 "欢迎大家访问我们的网站</a></br>" +
    				 "<img src=\"cid:it315_logo_gif\">";
    
    public static void main(String[] args) throws Exception
	{
		String server = "smtp.sina.com.cn";
		String user = "it315_test";
		String pass = "123456";

        HtmlMessageSender sender = new HtmlMessageSender ();
        Session session = sender.createSession();
        MimeMessage message = sender.createMessage(session);
        
        //获得Transport对象,并连接邮件服务器发送邮件
        Transport transport = session.getTransport();
        transport.connect(server, user, pass);
        transport.sendMessage(message,
            message.getRecipients(Message.RecipientType.TO));
        transport.close();
	}

    public Session createSession()
    {
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", protocol);
		/*必须将mail.smtp.auth属性设置为true,SMTPTransport对象才会向
		SMTP服务器提交用户认证信息,这个信息可以从JavaMail的javadocs文档
		中的com.sun.mail.smtp包的帮助页面内查看到。
		*/
        props.setProperty ("mail.smtp.auth","true");
        Session session = Session.getInstance(props);
        session.setDebug(true);
    	return session;
    }

    public MimeMessage createMessage(Session session) throws Exception
    {
        MimeMessage message = new MimeMessage(session);    
        message.setFrom(new InternetAddress(from));
        message.setRecipients(Message.RecipientType.TO,
        		InternetAddress.parse(to));
        message.setSubject(subject);

        MimeMultipart multipart = new MimeMultipart("related");

        MimeBodyPart htmlBodyPart = new MimeBodyPart();          
        htmlBodyPart.setContent(body,"text/html;charset=gb2312");
        multipart.addBodyPart(htmlBodyPart); 

        MimeBodyPart gifBodyPart = new MimeBodyPart();
        FileDataSource fds = new FileDataSource("d:\\attach\\logo.gif");
        gifBodyPart.setDataHandler(new DataHandler(fds));
        gifBodyPart.setContentID("it315_logo_gif");
        multipart.addBodyPart(gifBodyPart);

        message.setContent(multipart);
        message.saveChanges();
        return message;
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -