ofbiz邮件配置

1.修改配置文件framework/common/config/general.properties,下面是配置好的
###############################################################################
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
###############################################################################

# -- unique instance id (20 char max)
unique.instanceId=ofbiz1

# -- the default currency to use for prices, etc
currency.uom.id.default=USD

# -- the default decimal format for currency
currency.decimal.format=##0.00

# -- locales made available separated by comma's
#locales.available=en,fr,nl

# -- the default country for drop downs
country.geo.id.default=USA

# -- the default trackingCodeId to use for Partner Managed Tracking Codes
partner.trackingCodeId.default=

# -- USPS address matching string - should be all lower case, no spaces, pipe delimited
usps.address.match=(^.*?p[\\. ]*o[\\. ]*box.*$)|(^.*?post.*?office.*?box.*$)|((^|(^.*? ))r[\\. ]*r[\\. ]*(( +)|([0-9#]+)).*$)|(^.*?rural.*?route.*$)

# -- mail notifications enabled (Y|N)
mail.notifications.enabled=Y//启用邮箱服务

# -- redirect all mail notifications to this address for testing
#mail.notifications.redirectTo=lamadong@163.com

# -- the default mail server to use
mail.smtp.relay.host=smtp.sina.com//邮箱服务地址

# -- SMTP Auth settings
mail.smtp.auth.user=lamadong
mail.smtp.auth.password=邮箱密码

# -- debug SMTP mail option enabled (Y|N)
mail.debug.on=Y

# -- HTTP upload max size in bytes (-1 for unlimited)
http.upload.max.size=-1

# -- spam header name and value to block incoming spam detected by external spam checker, configured for spam assin
mail.spam.name=X-Spam-Flag
mail.spam.value=YES

2.页面
<form name="alipaysubmit" method="post" action="<@ofbizUrl>sendemail</@ofbizUrl>">         
             <input type=hidden name="body" value="receive me mail to call me ">消息内容
             <input type=hidden name="sendTo" value="lamadong@163.com">收件人
            <input type=hidden name="sendFrom" value="lamadong@sina.com">发件人
            <input type=hidden name="subject" value="OFBiz Mail service">主题     
            <input type='submit' name='v_action' value='sendEmail'>     
  </form>
3.controller.xml配置
<request-map uri="sendemail">
        <security https="false" auth="false"/>
        <event type="service" path="" invoke="sendMail"/><!-- OFBiz已配置好的服务-->
        <response name="success" type="view" value="main"/>
    </request-map>
4.services_email.xml
<service name="sendMailInterface" engine="interface" location="" invoke="">
        <description>Interface service for mail services.  contentType defaults to "text/html", sendType defaults to
            "mail.smtp.host".  sendVia must be specified if sendType is different.  Configured in general.properties</description>
        <attribute name="sendTo" type="String" mode="IN" optional="true"/>
        <attribute name="sendCc" type="String" mode="IN" optional="true"/>
        <attribute name="sendBcc" type="String" mode="IN" optional="true"/>
        <attribute name="sendFrom" type="String" mode="IN" optional="false"/>
        <attribute name="subject" type="String" mode="IN" optional="false"/>
        <attribute name="authUser" type="String" mode="IN" optional="true"/>
        <attribute name="authPass" type="String" mode="IN" optional="true"/>
        <attribute name="sendVia" type="String" mode="IN" optional="true"/>
        <attribute name="sendType" type="String" mode="IN" optional="true"/>
        <attribute name="contentType" type="String" mode="INOUT" optional="true"/>
        <attribute name="subject" type="String" mode="OUT" optional="true"/>
        <attribute name="partyId" type="String" mode="INOUT" optional="true"/>
    </service>
    <service name="sendMail" engine="java"
            location="org.ofbiz.content.email.EmailServices" invoke="sendMail">
        <description>Send E-Mail Service.  partyId and communicationEventId aren't used by sendMail
            but are passed down to storeEmailAsCommunication during the SECA chain.  See sednMailInterface for more comments.</description>
        <implements service="sendMailInterface"/>
        <attribute name="body" type="String" mode="INOUT" optional="false"/>
        <attribute name="communicationEventId" type="String" mode="INOUT" optional="true"/>
        <override name="contentType" mode="INOUT"/>
        <override name="subject" mode="INOUT" optional="false"/>
    </service>
5.类方法
 public static Map sendMail(DispatchContext ctx, Map context) {
          Map results = ServiceUtil.returnSuccess();
        String subject = (String) context.get("subject");
        String partyId = (String) context.get("partyId");
        String body = (String) context.get("body");
        List bodyParts = (List) context.get("bodyParts");
        GenericValue userLogin = (GenericValue) context.get("userLogin");

        results.put("partyId", partyId);
        results.put("subject", subject);
        if (UtilValidate.isNotEmpty(body)) results.put("body", body);
        if (UtilValidate.isNotEmpty(bodyParts)) results.put("bodyParts", bodyParts);
        results.put("userLogin", userLogin);

        // first check to see if sending mail is enabled
        String mailEnabled = UtilProperties.getPropertyValue("general.properties", "mail.notifications.enabled", "N");
        if (!"Y".equalsIgnoreCase(mailEnabled)) {
            // no error; just return as if we already processed
            Debug.logImportant("Mail notifications disabled in general.properties; here is the context with info that would have been sent: " + context, module);
            return results;
        }
        String sendTo = (String) context.get("sendTo");
        String sendCc = (String) context.get("sendCc");
        String sendBcc = (String) context.get("sendBcc");

        // check to see if we should redirect all mail for testing
        String redirectAddress = UtilProperties.getPropertyValue("general.properties", "mail.notifications.redirectTo");
        if (UtilValidate.isNotEmpty(redirectAddress)) {
            String originalRecipients = " [To: " + sendTo + ", Cc: " + sendCc + ", Bcc: " + sendBcc + "]";
            subject = subject + originalRecipients;
            sendTo = redirectAddress;
            sendCc = null;
            sendBcc = null;
        }

        String sendFrom = (String) context.get("sendFrom");
        String sendType = (String) context.get("sendType");
        String sendVia = (String) context.get("sendVia");
        String authUser = (String) context.get("authUser");
        String authPass = (String) context.get("authPass");
        String contentType = (String) context.get("contentType");

        boolean useSmtpAuth = false;

        // define some default
        if (sendType == null || sendType.equals("mail.smtp.host")) {
            sendType = "mail.smtp.host";
            if (sendVia == null || sendVia.length() == 0) {
                sendVia = UtilProperties.getPropertyValue("general.properties", "mail.smtp.relay.host", "localhost");
            }
            if (authUser == null || authUser.length() == 0) {
                authUser = UtilProperties.getPropertyValue("general.properties", "mail.smtp.auth.user");
            }
            if (authPass == null || authPass.length() == 0) {
                authPass = UtilProperties.getPropertyValue("general.properties", "mail.smtp.auth.password");
            }
            if (authUser != null && authUser.length() > 0) {
                useSmtpAuth = true;
            }
        } else if (sendVia == null) {
            return ServiceUtil.returnError("Parameter sendVia is required when sendType is not mail.smtp.host");
        }


        if (contentType == null) {
            contentType = "text/html";
        }

        if (UtilValidate.isNotEmpty(bodyParts)) {
            contentType = "multipart/mixed";
        }
        results.put("contentType", contentType);

        try {
            Properties props = System.getProperties();
            props.put(sendType, sendVia);
            if (useSmtpAuth) {
                props.put("mail.smtp.auth", "true");
            }

            Session session = Session.getInstance(props);
            boolean debug = UtilProperties.propertyValueEqualsIgnoreCase("general.properties", "mail.debug.on", "Y");
            session.setDebug(debug);                       

            MimeMessage mail = new MimeMessage(session);
            mail.setFrom(new InternetAddress(sendFrom));
            mail.setSubject(subject);
            mail.setHeader("X-Mailer", "Apache OFBiz, The Apache Open For Business Project");
            mail.setSentDate(new Date());
            mail.addRecipients(Message.RecipientType.TO, sendTo);

            if (UtilValidate.isNotEmpty(sendCc)) {
                mail.addRecipients(Message.RecipientType.CC, sendCc);
            }
            if (UtilValidate.isNotEmpty(sendBcc)) {
                mail.addRecipients(Message.RecipientType.BCC, sendBcc);
            }

            if (UtilValidate.isNotEmpty(bodyParts)) {
                // check for multipart message (with attachments)
                // BodyParts contain a list of Maps items containing content(String) and type(String) of the attachement
                MimeMultipart mp = new MimeMultipart();
                Debug.logInfo(bodyParts.size() + " multiparts found",module);
                Iterator bodyPartIter = bodyParts.iterator();
                while (bodyPartIter.hasNext()) {
                    Map bodyPart = (Map) bodyPartIter.next();
                    Object bodyPartContent = bodyPart.get("content");
                    MimeBodyPart mbp = new MimeBodyPart();

                    if (bodyPartContent instanceof String) {
                        StringDataSource sdr = new StringDataSource((String) bodyPartContent, (String) bodyPart.get("type"));
                        Debug.logInfo("part of type: " + bodyPart.get("type") + " and size: " + bodyPart.get("content").toString().length() , module);
                        mbp.setDataHandler(new DataHandler(sdr));
                    } else if (bodyPartContent instanceof byte[]) {
                        ByteArrayDataSource bads = new ByteArrayDataSource((byte[]) bodyPartContent, (String) bodyPart.get("type"));
                        Debug.logInfo("part of type: " + bodyPart.get("type") + " and size: " + ((byte[]) bodyPartContent).length , module);
                        mbp.setDataHandler(new DataHandler(bads));
                    } else {
                        mbp.setDataHandler(new DataHandler(bodyPartContent, (String) bodyPart.get("type")));
                    }

                    String fileName = (String) bodyPart.get("filename");
                    if (fileName != null) {
                        mbp.setFileName(fileName);
                    }
                    mp.addBodyPart(mbp);
                }
                mail.setContent(mp);
                mail.saveChanges();
            } else {
                // create the singelpart message
                mail.setContent(body, contentType);
                mail.saveChanges();
            }

            Transport trans = session.getTransport("smtp");
            if (!useSmtpAuth) {
                trans.connect();
            } else {
                trans.connect(sendVia, authUser, authPass);
            }
            trans.sendMessage(mail, mail.getAllRecipients());
            trans.close();
        } catch (Exception e) {
            String errMsg = "Cannot send email message to [" + sendTo + "] from [" + sendFrom + "] cc [" + sendCc + "] bcc [" + sendBcc + "] subject [" + subject + "]";
            Debug.logError(e, errMsg, module);
            Debug.logError(e, "Email message that could not be sent to [" + sendTo + "] had context: " + context, module);
            return ServiceUtil.returnError(errMsg);
        }
        return results;
    }

 

如果是电子商务里的邮件配置,还要把店铺的电子邮件选项里的取回密码的邮箱配置为general.properties里的邮箱一样.


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值