发送电子邮件

/**
 * 发送电子邮件
 */
public class SendMailUtil {

    // private static final String smtphost = "192.168.1.70";
    private static final String from = "thinkgem@163.com";
    private static final String fromName = "测试公司";
    private static final String charSet = "utf-8";
    private static final String username = "thinkgem@163.com";
    private static final String password = "123456";

    private static Map<String, String> hostMap = new HashMap<String, String>();
    static {
        // 126
        hostMap.put("smtp.126", "smtp.126.com");
        // qq
        hostMap.put("smtp.qq", "smtp.qq.com");

        // 163
        hostMap.put("smtp.163", "smtp.163.com");

        // sina
        hostMap.put("smtp.sina", "smtp.sina.com.cn");

        // tom
        hostMap.put("smtp.tom", "smtp.tom.com");

        // 263
        hostMap.put("smtp.263", "smtp.263.net");

        // yahoo
        hostMap.put("smtp.yahoo", "smtp.mail.yahoo.com");

        // hotmail
        hostMap.put("smtp.hotmail", "smtp.live.com");

        // gmail
        hostMap.put("smtp.gmail", "smtp.gmail.com");
        hostMap.put("smtp.port.gmail", "465");
    }

    public static String getHost(String email) throws Exception {
        Pattern pattern = Pattern.compile("\\w+@(\\w+)(\\.\\w+){1,2}");
        Matcher matcher = pattern.matcher(email);
        String key = "unSupportEmail";
        if (matcher.find()) {
            key = "smtp." + matcher.group(1);
        }
        if (hostMap.containsKey(key)) {
            return hostMap.get(key);
        } else {
            throw new Exception("unSupportEmail");
        }
    }

    public static int getSmtpPort(String email) throws Exception {
        Pattern pattern = Pattern.compile("\\w+@(\\w+)(\\.\\w+){1,2}");
        Matcher matcher = pattern.matcher(email);
        String key = "unSupportEmail";
        if (matcher.find()) {
            key = "smtp.port." + matcher.group(1);
        }
        if (hostMap.containsKey(key)) {
            return Integer.parseInt(hostMap.get(key));
        } else {
            return 25;
        }
    }

    /**
     * 发送模板邮件
     * 
     * @param toMailAddr
     *            收信人地址
     * @param subject
     *            email主题
     * @param templatePath
     *            模板地址
     * @param map
     *            模板map
     */
    public static void sendFtlMail(String toMailAddr, String subject,
            String templatePath, Map<String, Object> map) {
        Template template = null;
        Configuration freeMarkerConfig = null;
        HtmlEmail hemail = new HtmlEmail();
        try {
            hemail.setHostName(getHost(from));
            hemail.setSmtpPort(getSmtpPort(from));
            hemail.setCharset(charSet);
            hemail.addTo(toMailAddr);
            hemail.setFrom(from, fromName);
            hemail.setAuthentication(username, password);
            hemail.setSubject(subject);
            freeMarkerConfig = new Configuration();
            freeMarkerConfig.setDirectoryForTemplateLoading(new File(
                    getFilePath()));
            // 获取模板
            template = freeMarkerConfig.getTemplate(getFileName(templatePath),
                    new Locale("Zh_cn"), "UTF-8");
            // 模板内容转换为string
            String htmlText = FreeMarkerTemplateUtils
                    .processTemplateIntoString(template, map);
            System.out.println(htmlText);
            hemail.setMsg(htmlText);
            hemail.send();
            System.out.println("email send true!");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("email send error!");
        }
    }

    /**
     * 发送普通邮件
     * 
     * @param toMailAddr
     *            收信人地址
     * @param subject
     *            email主题
     * @param message
     *            发送email信息
     */
    public static void sendCommonMail(String toMailAddr, String subject,
            String message) {
        HtmlEmail hemail = new HtmlEmail();
        try {
            hemail.setHostName(getHost(from));
            hemail.setSmtpPort(getSmtpPort(from));
            hemail.setCharset(charSet);
            hemail.addTo(toMailAddr);
            hemail.setFrom(from, fromName);
            hemail.setAuthentication(username, password);
            hemail.setSubject(subject);
            hemail.setMsg(message);
            hemail.send();
            System.out.println("email send true!");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("email send error!");
        }

    }

    public static String getHtmlText(String templatePath,
            Map<String, Object> map) {
        Template template = null;
        String htmlText = "";
        try {
            Configuration freeMarkerConfig = null;
            freeMarkerConfig = new Configuration();
            freeMarkerConfig.setDirectoryForTemplateLoading(new File(
                    getFilePath()));
            // 获取模板
            template = freeMarkerConfig.getTemplate(getFileName(templatePath),
                    new Locale("Zh_cn"), "UTF-8");
            // 模板内容转换为string
            htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(
                    template, map);
            System.out.println(htmlText);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return htmlText;
    }

    private static String getFilePath() {
        String path = getAppPath(SendMailUtil.class);
        path = path + File.separator + "mailtemplate" + File.separator;
        path = path.replace("\\", "/");
        System.out.println(path);
        return path;
    }

    private static String getFileName(String path) {
        path = path.replace("\\", "/");
        System.out.println(path);
        return path.substring(path.lastIndexOf("/") + 1);
    }

//  @SuppressWarnings("unchecked")
    public static String getAppPath(Class<?> cls) {
        // 检查用户传入的参数是否为空
        if (cls == null)
            throw new java.lang.IllegalArgumentException("参数不能为空!");
        ClassLoader loader = cls.getClassLoader();
        // 获得类的全名,包括包名
        String clsName = cls.getName() + ".class";
        // 获得传入参数所在的包
        Package pack = cls.getPackage();
        String path = "";
        // 如果不是匿名包,将包名转化为路径
        if (pack != null) {
            String packName = pack.getName();
            // 此处简单判定是否是Java基础类库,防止用户传入JDK内置的类库
            if (packName.startsWith("java.") || packName.startsWith("javax."))
                throw new java.lang.IllegalArgumentException("不要传送系统类!");
            // 在类的名称中,去掉包名的部分,获得类的文件名
            clsName = clsName.substring(packName.length() + 1);
            // 判定包名是否是简单包名,如果是,则直接将包名转换为路径,
            if (packName.indexOf(".") < 0)
                path = packName + "/";
            else {// 否则按照包名的组成部分,将包名转换为路径
                int start = 0, end = 0;
                end = packName.indexOf(".");
                while (end != -1) {
                    path = path + packName.substring(start, end) + "/";
                    start = end + 1;
                    end = packName.indexOf(".", start);
                }
                path = path + packName.substring(start) + "/";
            }
        }
        // 调用ClassLoader的getResource方法,传入包含路径信息的类文件名
        java.net.URL url = loader.getResource(path + clsName);
        // 从URL对象中获取路径信息
        String realPath = url.getPath();
        // 去掉路径信息中的协议名"file:"
        int pos = realPath.indexOf("file:");
        if (pos > -1)
            realPath = realPath.substring(pos + 5);
        // 去掉路径信息最后包含类文件信息的部分,得到类所在的路径
        pos = realPath.indexOf(path + clsName);
        realPath = realPath.substring(0, pos - 1);
        // 如果类文件被打包到JAR等文件中时,去掉对应的JAR等打包文件名
        if (realPath.endsWith("!"))
            realPath = realPath.substring(0, realPath.lastIndexOf("/"));
        /*------------------------------------------------------------ 
         ClassLoader的getResource方法使用了utf-8对路径信息进行了编码,当路径 
          中存在中文和空格时,他会对这些字符进行转换,这样,得到的往往不是我们想要 
          的真实路径,在此,调用了URLDecoder的decode方法进行解码,以便得到原始的 
          中文及空格路径 
        -------------------------------------------------------------*/
        try {
            realPath = java.net.URLDecoder.decode(realPath, "utf-8");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println("realPath----->" + realPath);
        return realPath;
    }

    // private static File getFile(String path){
    // File file =
    // SendMail.class.getClassLoader().getResource("mailtemplate/test.ftl").getFile();
    // return file;
    // }
    //

    public static void main(String[] args) {
        // HtmlEmail hemail = new HtmlEmail();
        // try {
        // hemail.setHostName("smtp.exmail.qq.com");
        // hemail.setCharset("utf-8");
        // hemail.addTo("fly.1206@qq.com");
        // hemail.setFrom("zhoujunfeng@et-bank.com", "周俊峰");
        // hemail.setAuthentication("zhoujunfeng@et-bank.com", "31415926@aa");
        // hemail.setSubject("sendemail test!");
        // hemail.setMsg("http://www.google.cn\">谷歌
");
// hemail.send(); // System.out.println("email send true!"); // } catch (Exception e) { // e.printStackTrace(); // System.out.println("email send error!"); // } Map<String, Object> map = new HashMap<String, Object>(); map.put("subject", "测试标题"); map.put("content", "测试 内容"); String templatePath = "mailtemplate/test.ftl"; sendFtlMail("test@163.com", "sendemail test!", templatePath, map); // System.out.println(getFileName("mailtemplate/test.ftl")); } }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: ABAP是一种用于SAP软件开发的编程语言,可以用于发送电子邮件。要在ABAP中发送电子邮件,可以按照以下步骤进行操作: 1. 设置邮件配置:首先,需要在ABAP系统中进行邮件配置。可以使用事务码SCOT来配置SMTP服务器和端口号,以及其他邮件服务器的相关信息。确保邮件服务器已正确配置。 2. 定义变量和对象:在ABAP程序中,需要定义一些变量和对象,用于存储和传递电子邮件相关的信息。例如,需要定义一个实例化的CL_BCS类对象来处理邮件发送功能。 3. 设置电子邮件的属性:在发送电子邮件之前,需要设置相关的属性,例如发件人、收件人、抄送、邮件主题、邮件正文等。通过设置这些属性,可以控制邮件的格式和内容。 4. 添加附件(可选):如果需要发送附件,可以通过添加附件来实现。可以使用函数模块SO_ATTACHMENT_INSERT来将附件添加到电子邮件中。 5. 发送邮件:当所有的邮件属性和附件设置完毕后,使用CL_BCS类中的SEND方法来发送电子邮件电子邮件将会根据设置的属性和内容被发送到指定的收件人。 6. 检查发送结果:发送邮件后,可以检查邮件的发送结果。可以使用CL_BCS类中的GET_SENT_MESSAGES方法来获取电子邮件发送的结果信息。 以上是使用ABAP发送电子邮件的基本步骤。在实际的开发中,可能还有其他的细节需要注意,例如设置邮件服务器的安全性、处理邮件发送失败的情况等。但总体来说,通过合适的配置和正确的代码编写,可以在ABAP中成功发送电子邮件。 ### 回答2: ABAP是一种针对SAP应用程序开发的编程语言,可以与SAP系统进行交互。在ABAP中,可以使用几种方法来发送电子邮件。 首先,可以使用SAP提供的Function Module(函数模块)来发送电子邮件。例如,使用函数模块SO_NEW_DOCUMENT_ATT_SEND_API1可以发送电子邮件,并且可以附加文件。这个函数模块可以设置电子邮件发送者、接收者、主题、正文和附件等信息。 其次,可以使用ABAP的邮件发送类CL_BCS来发送电子邮件。CL_BCS是SAP提供的一个类,可以方便地发送电子邮件。你可以通过实例化CL_BCS类,并设置电子邮件的相关属性,例如发送者、接收者、主题、正文和附件等。然后,可以调用该类的SEND方法来发送邮件。 第三种方法是使用SMTP服务器发送电子邮件。在ABAP中,可以使用函数模块INTERNET_SMTP_MAIL发送电子邮件。通过设置相关参数,例如SMTP服务器地址、发送者、接收者、主题和正文等,可以使用该函数模块发送邮件。 无论使用哪种方法,发送电子邮件之前,需要确保SAP系统已经配置了正确的邮件服务器参数,并且相应的授权已经设置。此外,还需要在后台任务管理器中设置最小运行时间,以便邮件可以发送成功。 综上所述,使用ABAP发送电子邮件有多种方法可供选择,根据具体情况选择合适的方法,并提供必要的参数,即可成功发送电子邮件。 ### 回答3: ABAP 是一种专门用于 SAP 系统的编程语言,可以在 SAP 系统内部使用 ABAP 编写各种程序和功能。发送电子邮件是其中的一项常见需求,下面我将使用 ABAP 来演示如何发送电子邮件。 首先,我们需要配置一个可用的 SAP 发件人邮件账户。在 SAP 系统中,可以通过访问交易码 SCOT 进行相关配置。在 SCOT 页面中,我们可以设置发送邮件所需的 SMTP 服务器和认证信息。 接下来,在 ABAP 程序中编写代码来发送邮件。我们可以使用函数模块 `SO_NEW_DOCUMENT_ATT_SEND_API1` 来发送带有附件的邮件。以下是一个示例代码: ```abap DATA: lv_sender TYPE sy-uname VALUE 'your_sender', lv_recipient TYPE ad_smtpadr, lt_attachment TYPE STANDARD TABLE OF solisti1, lw_attachment TYPE solisti1, lv_subject TYPE so_obj_des, lv_text TYPE soli_tab, lt_receivers TYPE STANDARD TABLE OF somlreci1, lw_receiver TYPE somlreci1. * 设置发件人和收件人 lv_recipient = 'your_recipient'. lw_receiver-receiver = lv_recipient. APPEND lw_receiver TO lt_receivers. * 设置邮件主题 lv_subject = '邮件主题'. * 设置邮件正文 lv_text = '邮件正文'. * 添加附件(可选) CLEAR lw_attachment. lw_attachment-obj_descr = '附件描述'. lw_attachment-obj_name = 'file_name.pdf'. "附件文件名 lw_attachment-obj_lang = 'ZH'. "附件语言 lw_attachment-obj_len = strlen( '附件内容' ). "附件内容长度 lw_attachment-objbin = '附件内容'. APPEND lw_attachment TO lt_attachment. * 发送邮件 CALL FUNCTION 'SO_NEW_DOCUMENT_ATT_SEND_API1' EXPORTING document_data = lw_send_request TABLES packing_list = lt_attachment object_header = lt_receivers contents_txt = lv_text contents_bin = lt_attachment EXCEPTIONS too_many_receivers = 1 document_not_sent = 2 document_type_not_exist = 3 operation_no_authorization = 4 parameter_error = 5 x_error = 6 enqueue_error = 7 OTHERS = 8. ``` 在上述示例中,我们定义了发件人、收件人、邮件主题、邮件正文和附件信息,并将其传递给函数模块 `SO_NEW_DOCUMENT_ATT_SEND_API1` 进行发送。请注意,发送邮件操作可能需要相应的权限和配置,具体情况需根据实际系统进行调整。 以上就是使用 ABAP 发送电子邮件的基本步骤和示例代码。通过以上的操作,我们可以在 SAP 系统中使用 ABAP 来发送电子邮件,并且可以添加附件等特性。希望对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值